Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Django explains the process from request to response

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains the "django from request to response process explanation", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "django from request to response process explanation" bar!

Django start

When we start a django project, whether you execute it on the command line or click to run it directly in pycharm, you are actually performing the operation of 'runserver', while ruserver uses the web server that comes with django, which is mainly used for development and debugging, while in a formal environment, you usually use nginx+uwsgi mode.

Either way, when you start a project, you do two things:

Create an instance of the WSGIServer class to accept the user's request.

When a user's http request arrives, specify a WSGIHandler for the user to handle the user's request and response, and this Handler is the core of processing the entire request.

WSGI

WSGI: Web Server Gateway Interface,WSGI is not a server, nor an API used to interact with a program, let alone code, but a specification that defines an interface that describes how web server communicates with web application.

When the client sends a request, the web server is actually the first to handle the request, which is the web server like nginx and Apache, which we often say, and then the web server hands the request to the web application (such as django). The intermediary is WSGI, which connects the web server with the web framework (Django).

Briefly introduce some of the contents of WSGI, which specifies that the application is a callable object (function / method), and then it accepts two fixed parameters: one contains server-side environment variables, and the other is a callable object, which is used to initialize the response, add the status code status code and httpt header to the response, and return a callable object. You can look at a simple example.

# this code comes from python core programming def simplr_wsgi_app (environ, start_response): # fixed two parameters, django also uses the same variable name status = '200OK' headers = [{' Content-type': 'text/plain'}] # initialize the response. You must call start_response (status, headers) # to return the iterable object return [' hello worldview'] before returning.

In django, the same logic is implemented through the WSGIHandler class, which we will focus on below!

If you are interested in WSGI and uWSGI, I recommend you to read this article, WSGI & uwsgi, great!

Basic concepts of middleware

As the name implies, middleware is located between the Web server side and the Web application, and it can add additional functions. When we create a django project (via pycharm), it automatically sets up some necessary middleware for us.

MIDDLEWARE_CLASSES = ['django.middleware.security.SecurityMiddleware',' django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware',' django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',' django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',' django.middleware.clickjacking.XFrameOptionsMiddleware',]

The middleware either preprocesses the data from the user and then sends it to the application, or makes some final adjustments to the resulting data before the application returns the response load to the user. To be popular, in django, the middle can help us prepare the request object, and then the application can directly use the request object to get all kinds of data, and also help us to add the response header, status code, and so on.

Data stream

When django receives a request, it initializes a WSGIHandler, which can be tracked in the wsgi.py file under the project, and you will find this class.

Class WSGIHandler (base.BaseHandler): def _ _ call__ (self, environ, start_response): pass

This class follows the rules of the WSGI application and accepts two parameters: one contains the server-side environment variable, and the other is a callable object that returns an iterable object.

This handler controls the whole process from request to response, the main flow:

See another picture on the Internet, which is more complete:

There are a few general steps:

1. The user requests a page through the browser

two。 The request arrives at Request Middlewares, and the middleware does some preprocessing to request or makes a direct response request.

3. URLConf finds the corresponding View through the urls.py file and the requested URL

4. When View Middlewares is accessed, it can also do some processing to request or return response directly.

5. Call functions in View

6. The methods in View can selectively access the underlying data through Models.

7. All Model-to-DB interactions are done through manager

8. Views can use a special Context if necessary

9. Context is passed to Template to generate pages

A.Template uses Filters and Tags to render the output

b. The output is returned to View

C.HTTPResponse is sent to Response Middlewares

d. Any Response Middlewares can enrich response or return a completely different response

E.Response returns to the browser and presents it to the user

Order and method in Intermediate Class

The middleware class of django contains at least one of the following four methods:

Process_request 、 process_view 、 process_exception 、 process_response

WSGIHandler adds these methods to the _ request_middleware, _ view_middleware, _ response_middleware, and _ exception_middleware lists through load_middleware.

Not every middleware has these four methods, and if a method does not exist, the class is skipped during loading.

For middleware_path in settings.MIDDLEWARE_CLASSES: if hasattr (mw_instance, 'process_request'): request_middleware.append (mw_instance.process_request) if hasattr (mw_instance,' process_view'): self._view_middleware.append (mw_instance.process_view) if hasattr (mw_instance, 'process_template_response'): self._template_response_middleware.insert (0, mw_instance.process_template_response) if hasattr (mw_instance 'process_response'): self._response_middleware.insert (0, mw_instance.process_response) if hasattr (mw_instance,' process_exception'): self._exception_middleware.insert (0, mw_instance.process_exception)

We can see from the source code that the loading order of process request and process response is exactly the opposite. In the loop, process_request is append to the end of the list, while process_request is insert to the front.

(there may be some cases where Comment middleware is in front of Session. It would be nice to know the loading order.)

Process_request

Give a few examples of middleware

Class CommonMiddleware (object): # pseudo code def process_request (self, request): # Check for denied User-Agents if 'HTTP_USER_AGENT' in request.META: for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search (request.META [' HTTP_USER_AGENT']): raise PermissionDenied ('Forbidden user agent') host = request.get_host () if settings.PREPEND_WWW and host and not host.startswith (' www.'): host = 'www.' + host pass

The process_request of CommonMiddleware is mainly to judge whether the user agent meets the requirements and to improve the URL, such as adding www or adding / at the end.

Class SessionMiddleware (object): def process_request (self, request): session_key = request.COOKIES.get (settings.SESSION_COOKIE_NAME) request.session = self.SessionStore (session_key)

SessionMiddleware's process_request is to take the session_key out of the cookies and put it into the request.session.

Class AuthenticationMiddleware (MiddlewareMixin): def process_request (self, request): assert hasattr (request, 'session'), ("The Django authentication middleware requires session middleware"to be installed. Edit your MIDDLEWARE%s setting to insert"' django.contrib.sessions.middleware.SessionMiddleware' before"'django.contrib.auth.middleware.AuthenticationMiddleware'.")% ("_ CLASSES" if settings.MIDDLEWARE is None else ") request.user = SimpleLazyObject (lambda: get_user (request))

As mentioned earlier, middleware is loaded in a certain order (positive and negative)

AuthenticationMiddleware's process_request method is loaded based on session middleware, and then the user is pulled out and put into request.user through request's session.

Process_request should return a None or HTTPResponse object. When None is returned, WSGI handler will continue to load the methods in process_request. In the latter case, Handlers will directly load the list of _ response_middleware and then response directly.

Parsing url

When the process_request in the _ request_middleware list is traversed, you get a processed request object (with attributes such as request.session,request.user).

Django will regularly match the url in order, and if the match is not successful, an exception will be thrown. If the middleware of request returns None, then Django parses the URL requested by the user.

In setting, there is a ROOT_URLCONF that points to the urls.py file, according to which you can produce a urlconf, which is essentially a mapping table between the url and the view function, and then parses the user's url through resolver to find the first matching view.

Process_view

After matching with url, the view function and related parameters are obtained. Before calling the view function, django loads each process_view method in _ view_middleware.

I looked at the default middleware one by one, and only saw that csrf had this method.

# pseudo code class CsrfViewMiddleware (object): def process_view (self, request, callback, callback_args, callback_kwargs): if getattr (request, 'csrf_processing_done', False): return None try: csrf_token = _ sanitize_token (request. COOKIES [settings.CSRF _ COOKIE_NAME]) # Use same token next time request.META [' CSRF_COOKIE'] = csrf_token except KeyError: csrf_token = None if getattr (callback, 'csrf_exempt', False): return None pass

The purpose of this method is to determine whether a field of csrf exists in the cookiers. If not, an exception is thrown directly, and if so, None is returned.

View middleware, like requst middleware, must return None or a httpResponse. If a httpresponse is returned, Handlers will directly load the list of _ response_middleware and then return HttpResponse, then Handlers will directly load the list of _ response_middleware and then directly response

Execute view logic

The view function needs to satisfy:

View based on function (FBV) or class based (CVB).

The first accepted parameter must be request and a response object needs to be returned.

If the view function throws an exception, Handler will loop through the _ exception_middleware list, and if an exception is thrown, the subsequent process_exception will not be executed.

Process_response

At this stage, we get a HTTPResponse object, which may be returned by process_view or by the view function. Now we will iterate through the response middleware. This is the last chance for middleware to adjust the data. For example:

Class XFrameOptionsMiddleware (object): def process_response (self, request, response): # Don't set it if it's already in the response if response.get ('Xmuri Frame options') is not None: return response # Don't set it if they used @ xframe_options_exempt if getattr (response, 'xframe_options_exempt', False): return response response [' Xmuri FrameMutual Options'] = self.get_xframe_options_value (request, response) return response

XFrameOptionsMiddleware adds X-Frame-Options to response to prevent websites from being nested and hijacked.

Class CsrfViewMiddleware (object): def process_response (self, request, response): if getattr (response, 'csrf_processing_done', False): return response if not request.META.get ("CSRF_COOKIE_USED", False): return response # Set the CSRF cookie even if it's already set, so we renew # the expiry timer. Response.set_cookie (settings.CSRF_COOKIE_NAME, request.META ["CSRF_COOKIE"], max_age=settings.CSRF_COOKIE_AGE, domain=settings.CSRF_COOKIE_DOMAIN, path=settings.CSRF_COOKIE_PATH, secure=settings.CSRF_COOKIE_SECURE, httponly=settings.CSRF_COOKIE_HTTPONLY) # Content varies with the CSRF cookie, so set the Vary header. Patch_vary_headers (response, ('Cookie',)) response.csrf_processing_done = True return response

CsrfViewMiddleware sets csrf cookies in response

Last

When the middleware of response is loaded, the system will call the start_response method object passed from the WSGI server before returning, initialize the response, and then make the response response.

Summary

The focus of this article is as follows:

When django starts, a WSGIserver is started and a handler is generated for each requested user.

Understand the WSGI protocol, and the WSGIHandler class controls the entire request-to-response process, as well as the basic process of the entire process.

The concept of middleware and the role of each process_request, process_response, process_view, process_exception method in which step.

The middle price is executed sequentially, request and view are executed sequentially, while response and exception are in reverse order, which is actually done by WSGIHandler when it is loaded into its lists.

Thank you for your reading, the above is the content of "the process of django from request to response". After the study of this article, I believe you have a deeper understanding of the process of django from request to response, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report