Django request Lifecycle

Source: Internet
Author: User
1. Overview

First, we know that all data transmitted in the HTTP request and server response is strings.

In Django, when we access a URL, it will enter the corresponding HTML Webpage through routing matching.

Django's request lifecycle refers to what happens in the Django background when the user enters the URL in the browser to the time when the user sees the webpage.

What happened in Django's lifecycle ??

1. when a user enters a URL in a browser, the browser will generate a request header and a request body. The request header and the request body will contain the browser action ), this action is usually get or post, which is reflected in the URL. 2. the URL passes through wsgi in Django, and then through Django's middleware. Finally, the URL goes to the route ing table and matches one of the routes. Once one of these matches successfully, the corresponding view function is executed, the subsequent routes will no longer match. 3. view functions query data based on client requests. 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 displays it to the user after rendering.

View functions query the corresponding data based on client requests. If multiple clients send different URLs to the server at the same time

After the server queries the data, how does one know which data is returned to which client ??

Therefore, the URL sent from the client to the server must contain the data information to be requested.

For example,http://www.aaa.com/index/?nid=userIn this URL,
The client sends a GET request to the servernid=userThe server canrequest.GET.get("nid")Obtain NID data

The client can also request data from the server through post.

When the client requests data from the server in the form of post, the requested data is contained in the request body, and the server uses the request. Post method to obtain the data the client wants.

It should be noted that request. Post converts the data in the Request body into a dictionary, and the data in the Request body exists as strings by default.
2. fbv and CBV Modes

A URL corresponds to a view function. This mode is called fbv (Function Base Views)

Apart from fbv, Django also has another mode called CBV (Class Base views), That is, a URL corresponds to a class

Example: request a webpage in CBV Mode

Route information:

urlpatterns = [    url(r‘^fbv/‘,views.fbv),    url(r‘^cbv/‘,views.CBV.as_view()),]

View function Configuration:

from django.views import Viewclass CBV(View):    def get(self,request):        return render(request, "cbv.html")    def post(self,request):        return HttpResponse("cbv.get")

Cbv.html webpage content:

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

Start the project and enterhttp://127.0.0.1:8000/cbv/, Press Enter. The webpage is as follows:

Enter "hello" in the input box and press Enter. The webpage is as follows:

In fbv mode, view functions are directly executed after URL matching is successful.

If the CBV mode is used, the corresponding class in the view function will be found after the URL match is successful, and then the class will return to the request header to find the corresponding classRequest Method.

If the client submits a request in the form of post, it executes the POST method in the class. If the client submits the request in the form of get, it executes the get method in the class.

Search for the URL sent by the user, and then execute the corresponding method query in the class to generate the data required by the user.

2.1 fbv request process

When you send a URL request, Django will traverse all records in the route ing table in sequence. Once one of the records in the route ing table matches successfully,
Execute the function name corresponding to the function in the view. This is the execution process of fbv.

2.2 CBV request process

When the server uses the CBV mode, the request sent by the user to the server contains the URL and method, both of which are string types.

After the server successfully matches the route ing table, it will automatically find the dispatch method, and Django will find the corresponding method in the class through the dispatch Reflection Method and execute

After the methods in the class are executed, the client will return the desired data to the dispatch method, and the dispatch method will return the data to the client

Example: Modify the view function in the preceding example to the following:

from django.views import Viewclass CBV(View):    def dispatch(self, request, *args, **kwargs):        print("dispatch......")        res=super(CBV,self).dispatch(request,*args,**kwargs)        return res    def get(self,request):        return render(request, "cbv.html")    def post(self,request):        return HttpResponse("cbv.get")

Print result:

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

Note that:

When you request data in get mode, there is information in the request header. When there is no data in the Request body to request data in post mode, there is data in the request header and request body.
3. Response content of Django request Lifecycle

HTTP data submission methods:"post","get","put","patch","delete","head","options","trace".

When submitting data, the server triggers different view functions based on different methods.

For the from form, only get and post methods are available for data submission.

The other method can be submitted through the Ajax method.

The server operates the database based on the individual request information. You can use native SQL statements or Django ORM statements.

Django queries and processes the desired data from the database, and returns the result to the user.

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

In Django, sometimes a view function uses httpresponse to return a string to the client after execution.
This string is only part of the response body. How should I set the Response Header returned to the client ???

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

Modify the view function in the preceding example as follows:

from django.views import Viewclass CBV(View):    def dispatch(self, request, *args, **kwargs):        print("dispatch......")        res=super(CBV,self).dispatch(request,*args,**kwargs)        print(res)        return res    def get(self,request):        return render(request, "cbv.html")    def post(self,request):        res=HttpResponse("cbv.post")        res.set_cookie("k2","v2")        res.set_cookie("k4","v4")        print("res:",res)        print("request.cookie:",request.COOKIES)        return res

Printed information:

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

 

Django request Lifecycle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.