Django source code analysis

1. wsgi: Interaction standard between webserver and app

    1. Enter env,

    2、callback(status header),  

    3. Return the body in the form of an array

 

def app(environ, start_response):

    start_response('200 OK', [('Content-Type', 'text/plain')])

    yield "Hello world!\n"

 

Second, the main process of processing

1. All applications are unified by django/core/handlers/wsgi.py WSGIHandler

2. WSGIHandler internally divides the entire processing into several stages

1" load_middleware (once during initialization)

request_middleware

self._view_middleware = []

 

# The last 3 are from back to front

       self._template_response_middleware = []

       self._response_middleware = []

       self._exception_middleware = []

   2" trigger the callback signals.request_started.send(sender=self.__class__, environ=environ)

    In fact, only the db part will be disconnected and reconnected

3" Construct WSGIRequest

4" get_response ----- main process

1. Call back process_request in turn, and interrupt if there is a return value, otherwise execute the next one

2. Find the view according to the url

3. Call process_view in turn

4. The specific callback, ----- must return the response

5. If there is a render, apply process_template_response (before using the template, you can modify the template related logic)

6. Use process_response ---- after generating the response

7. When there is an exception in this process, trigger process_exception

简单说:process_request parseUrl process_view callback process_template_response render process_response

3. How to keep db connection alive? Directly do not keep alive

django.db.backends.base.base.py BaseDatabaseWrapper get_new_connection

django.db.models.sql.compiler.py execute_sql 

 

The default is to open a new database connection for each request, and then close (stateless). If you want to maintain it, pay attention to setting the state and quantity limit of the connection

 

Third, the directory structure of a typical app

manager.py -- specify the setting file

project

    settings

    urls

    sleep

    tests

app

    models

    views

    urls

    apps

    admin

static

template

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326058010&siteId=291194637