SoFunction
Updated on 2024-11-19

Django Framework Request Lifecycle Implementation Principles

Let's look at a picture first!

1. Request life cycle

- wsgi, which is a socket server that receives user requests and encapsulates them for the first time, then passes them on to web frameworks (Flask, Django)

- Middleware that helps us to validate the request or add other relevant data to the request object, e.g. csrf,

- route matching

- View functions, where business logic is handled, may involve: orm, templates => rendering

- Middleware that processes the response data.

- wsgi, sends the response to the browser.

2. what wsgi

wsgi:web services gateway interface

module that implements the protocol:

  • - wsgiref (beta version with exceptionally poor performance)
  • - werkzurg
  • - uwsig

wsgiref example:

from wsgiref.simple_server import make_server
 
def run_server(environ, start_response):
  start_response('200 OK', [('Content-Type', 'text/html')])
  return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ] # bytes
 
 
if __name__ == '__main__':
  httpd = make_server('127.0.0.1', 8000, run_server)
  httpd.serve_forever()

werkzeug example:

from  import Response
from  import run_simple
 
def run_server(environ, start_response):
  response = Response('hello')
  return response(environ, start_response)   #Objects
 
if __name__ == '__main__':
  run_simple('127.0.0.1', 8000, run_server)

3. View FBV

url - function

CBV

url - view

FBV (function base view) and CBV (class base view) are essentially the same, except that fbv is function based and cbv is class based. Only fbv more than cbv back a few more steps.

4、rest-framework

The rest-framework intervenes from the dispatch method, executes the view, and executes the rest-framework component if there is one.

5. restfui specification

View restful specification details

This is the whole content of this article.