Django - Lifecycle of Requests & Templates & Routing

Keywords: Python Django Database SQL Session

Lifecycle requested in Django

1. Overview

First, we know that all data transferred in HTTP requests and server responses is strings.

In Django, when we visit a url, we enter the corresponding html page through route matching.

Django's request life cycle is what happens behind the scenes when a user enters a url into the browser and the user sees the web page

What exactly happened during Django's life cycle?

1. When a user enters a url in the browser, the browser generates a request header and a request body to send to the server
 The request header and body contain the browser's action, which is usually a get or post, reflected in the url.

2. The url passes through wsgi in Django, then through Django's middleware, and finally through the route map, matching one by one in the route.
Once one of the matches succeeds, the corresponding view function is executed, and subsequent routes will no longer match.
3. View functions query the data according to the client's request. Return to Django, and Django returns the data the client wants as a string to the client.
4. The client browser receives the returned data and renders it to the user.

After the view function queries the data according to the client's request, if there are multiple clients sending different URLs to the server at the same time

After the server queries the data, how do you know which data to return to which client?

Therefore, the url sent by the client to the server must also contain the requested data information and so on.

For example,Http:// this url,
A nid=user request sent by a client to a server through a get request, and the server canRequest.GET.getGetting NID data by ("nid")

Clients can also post data to the server.

When a client requests data from a server in the form of a post, the requested data is contained in the body of the request, and the server uses itRequest.POSTHow to get the data the client wants

It is important to note that,Request.POSTIs to convert the data in the body of a request into a dictionary, and the data in the body of the request exists as a string by default.

2. FBV mode and CBV mode

A url corresponds to a view function, and this pattern is called FBV(Function Base Views)

In addition to FBV, there is another pattern in Django called CBV(Class Base views), where a url corresponds to a class

Example: Use cbv mode to request web pages

Routing information:

urlpatterns = [

View function configuration:

from django.views import View

class CBV(View):
	def get(self,request):
		return render(request, "cbv.html")

	def post(self,request):
		return HttpResponse("cbv.get")

Cbv.htmlContent of the Web page:

<form method="post" action="/cbv/">
    {% csrf_token %}
	<input type="text">
	<input type="submit">

Start the project and type in the browserHttp://, Enter, get the following web page:

Enter "hello" in the input box and return to get the following page:

Using the fbv pattern, the corresponding view function is executed directly after the url matches successfully.

If you use cbv mode, after the url matches successfully, the corresponding class in the view function is found, and then the class returns to the request header to find the corresponding Request Method.

If the client submits the request as a post, execute the post method in the class;
If the client submits the request as a get, execute the get method in the class

It then finds the url sent by the user and executes the corresponding method query in the class to generate the data the user needs.

2.1 fbv Request Procedure

When a user sends a url request, Django iterates through all the records in the routing map table in turn, and once one of the records in the routing map matches successfully,
This is the fbv execution process for the corresponding function name in the execution view function

2.2 cbv Request Procedure

When the server uses cbv mode, requests from the user to the server include url and method, both of which are string types

The dispatch method is automatically found by the server when the route map matches successfully, and then Django finds the corresponding method in the class by dispatch reflection and executes it

Once the method in the class is executed, the data the client wants is returned to the dispatch method, which returns the data to the client

For example, modify the view function in the above example to be as follows:

from django.views import View

class CBV(View):
    def dispatch(self, request, *args, **kwargs):
        return res

    def get(self,request):
        return render(request, "cbv.html")

    def post(self,request):
        return HttpResponse("cbv.get")

Print results:

<HttpResponse status_code=200, "text/html; charset=utf-8">
<HttpResponse status_code=200, "text/html; charset=utf-8">

Note that:

When requesting data as get, there is information in the request header and no data in the request body
 When requesting data with post, both the request header and the request body have data.	

3. Response content for Django request lifecycle

http submits data in "post","get","put","patch","delete","head","options","trace".

When submitting data, the server triggers different view functions depending on the method.

For from forms, there are only get and post methods for submitting data

Another way to submit is through the Ajax method

The server operates the database according to the information requested by the individual, using either native SQL statements or Django ORM statements.

Django finished processing the data the user wanted from the database query and returned the result to the user.

The response content returned from Django contains the response header and body

In Django, sometimes a view function is executed and HttpResponse is used to return a string to the client.
This string is only part of the response body. How should the part of the response header returned to the client be set???

Add a response header for the information returned to the client:

Modify the view function of the above example as follows:

from django.views import View

class CBV(View):
	def dispatch(self, request, *args, **kwargs):

		return res

	def get(self,request):
		return render(request, "cbv.html")

	def post(self,request):


		return res

Printed information:

res: <HttpResponse status_code=200, "text/html; charset=utf-8">
request.cookie: {'csrftoken': 'jmX9H1455MYzDRQs8cQLrA23K0aCGoHpINL50GnMVxhUjamI8wgmOP7D2wXcpjHb', 'k2': 'v2', 'k4': 'v4'}

View Layer

1. HTTP requests

HttpRequest object

request.path			#When using the GET method, only paths are obtained.
request.get_full_path() #When using the GET method, you get full paths that include information such as paths and?, =.
request.method  		#HTTP method for client requesting web pages: POST or GET
request.GET     		#Class dictionary object containing GET methods for all HTTP requests
request.POST			#Class dictionary object containing POST methods for all HTTP requests
request.COOkIES 		#A dictionary object containing cookies whose keys and values are strings
request.sessions		#Unique readable and writable class dictionary object representing current session information with the server
request.body			#POST raw data for complex processing of data
request.has_key()		#Boolean, IdentityRequest.GETorRequest.POSTWhether to include the specified key
request.is_secure()		#Is the client's request secure
request.user			#On behalf of the currently logged-in userDjango.contrib.auth.Models.Userobject

request.FILES			#Class dictionary object for files uploaded through the form
	|--> request.FILES.get('filename')		#File name of uploaded file
    |--> request.FILES.get('content_type') 	#Content prototype of uploaded file
    |--> request.FILES.get('content')		#The original content of the uploaded file
META					#A dictionary containing all valid HTTP header information
	|--> content_length		#Length of data received
    |--> content_type		#Type of data received
    |--> query_string		#The original request string received
    |--> remote_addr		#IP address of client
    |--> remote_host		#Host name of client
    |--> remote_name		#Host name of the server
    |--> remote_port		#Port number of the server
    |--> http_host			#HST header information sent by client
    |--> http_referer		#Pointed Page
    |--> http_user_agent	#Information about browsers used by clients
    |--> http_x_bender		#X_bender header information

2. HTTP response

HttpResponse object

locals()		#Pass all variables in the view function to the template
# Method:
redirect()		#Redirection method, jump to another page
HttpResponse()	#Returns a string to the client
	|--> template_name	# Required parameter template name
    |--> context		# Optional parameter Developer can add a dictionary information to the template to prompt the user, default is an empty dictionary
    |--> content_type	# Optional parameter MIME type for document generation
    |--> status			# Optional parameter Response status code, default value 200
    |--> useing			# Optional parameter is the name of the template engine used to load the template


#Single Route Assignment
#Regular-based routing assignment
#Add additional parameters
#Route Mapping Settings Name
#Routing Branch

Posted by strangebeer on Tue, 09 Jun 2020 19:18:49 -0700