[Oldboy-django] [2 in-depth Django] Django a request lifecycle + WSGI + middleware

Source: Internet
Author: User

1 WSGI

#WSGI (is a set of protocols, many things such as Wsgiref, uwsgiref follow this set of protocols)-the Django system is essentially someone's socket (wsgiref or uwsgiref)+Django-The simple definition of WSGI (Web server Gateway Interface) is a specification that defines the interface format between Web apps and Web servers written in Python, enabling Web apps and Web Ser    Decoupling between the Ver. -more complete Web request life-cycle requests--Follow the WSGI socket server (WSGIREF)--->django middleware---> Routing system--->View Function View functions---> Routing systems---> Middleware--->wsgi--->Client-examples of Django-borrowed WSGIREF servers fromWsgiref.simple_serverImportMake_serverdefrunserver (environ, start_response):"""@params: Information about the environ request @params: Start_response container that returns the contents as a message header to the user @ret The contents returned by the urn are returned as the body of the message to the user"""Start_response ('OK', [('Content-type','text/html')])            return[Bytes ('', encoding='Utf-8'), ]        if __name__=='__main__': httpd= Make_server ("', 8000, Runserver) httpd.serve_forever ()#wait for the socket request of the service, execute the Runserver function when the request comes over-a simple socket serverImportSocketdefhandle_request (client): BUF= CLIENT.RECV (1024) Client.send ("http/1.1 ok\r\n\r\n") Client.send ("Hello, Seven.")        defMain (): Sock=Socket.socket (socket.af_inet, socket. Sock_stream) Sock.bind (('localhost', 8000)) Sock.listen (5)             whiletrue:connection, Address=sock.accept () handle_request (connection) connection.close ()if __name__=='__main__': Main ()
View Code

2 Django Full life cycle of a request

   - Django The lifecycle of a request        is simply: Wsgi and Django        client -->request--->wsgi---> All middleware (middleware process_request)--->process_view----> Views---        >urls---> All middleware ( Middleware process_response)--->wsgi---> client        PS: Process_ in middleware The request already knows which view function to execute (according to request, get the URL, get the corresponding view function according to the URL)
View Code

3 middleware

#Middleware-the life cycle of a Django request is simply: Wsgi and the Django client-->request--->wsgi---> All middleware (middleware process_request)--->process_view----> views--->urls---> All middleware (middleware process_response)--->wsgi--->Client PS: In the middleware process_request already know which view function to execute (according to request has obtained the URL, according to the URL to get the corresponding view function)-Define your own middleware class Mymiddle (middleware is a class) fromDjango.utils.deprecationImportmiddlewaremixin fromDjango.shortcutsImportRender,httpresponseclassMyMiddle1 (middlewaremixin):defprocess_request (self, request):Print('m1.process.request')            defProcess_view (self, request,callback, Callback_args, Callback_kwargs):Print('M1.process_view')                Print(callback)#This callback, is the URL corresponding to the view function                #return callback (Request, *callback_args, **callback_kwargs)            defProcess_response (self, request, response):Print('M1.processs.response')                returnResponse#You must have this, or you'll get an error.            defprocess_exception (self, request, exception):Print('m1.process_exception')                #print (Exception)        classMyMiddle2 (middlewaremixin):defprocess_request (self, request):Print('m2.process.request')            defProcess_view (Self,request, Callback, Callback_args, Callback_kwargs):Print('M2.process_view')            defProcess_response (self, request, response):Print('M2.processs.response')                returnResponse#You must have this, or you'll get an error.            defprocess_exception (self, request, exception):Print('m2.process_exception')                #print (Exception)-Register Middleware Middleware= [            #omit the previous section, append the next two            'Mid. MyMiddle1',            'Mid. MyMiddle2',        ]    -Full lifecycle HTTPS for a request:www.processon.com/diagraming/5a0ce2bae4b06bed41d126e1 Normal Flow: m1.process.request m2.process.request M1.proce        Ss_view m2.process_view views M2.processs.response m1.processs.response If there is exception:m1.process.request m2.process.request M1.process_view m2.proces            S_view views M2.process_exception m1.process_exception M2.processs.response M1.processs.response-Middleware Applications unify all requests (or part of a request) (such as caching)--can use the middleware implementation of each request to make a judgment, if the cache has, return, otherwise to the views read the database,
View Code

[Oldboy-django] [2 in-depth Django] Django a request lifecycle + WSGI + middleware

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.