Basic process principle of Python Django 01

Time:2020-10-30

Basic process principle of Python Django

The use of Django framework in Python

1、 Frame structure

Project name fruitcar

installdjangoThen execute the instruction

django-admin startproject FruitCar

The following directory structure is generated:

Containers for the fruitcar project(You can rename it)Fruitcar contains your project, which is a pure Python package. Its name is the python package name you need to use when you refer to anything inside it.Py is an empty file that tells python that this directory should be considered a python package.Configuration file for py Django project.Py routing profile.Entry point for py project running on WSGI compatible web server(When the front and back ends are not separated, the front page part is put here)
    manage.Py command line tool for managing Django projects

After you create a project, you can start it with the following command

 python manage.py runserver

Broadcast start mode of specific port:

 python manage.py runserver 0.0.0.0:8001
 //0.0.0.0It is not a real IP address, it represents all the IPv4 addresses in the local machine. monitor0.0.0.0Is the port that listens to all IP addresses in this machine

At this stage, the framework of our project is basically passed, and we have finished writing several static pages and putting a project on it. But our goal is to develop functions, so we need to go out and create apps. It’s customary for each big function to be divided into an app, which will make the project clear and conducive to project management and development.

For example, in my project, I want to manage vehicles and fruits. I create a car app and a fruit app to handle their respective logical functions in each app.

If there are_init_The. Py file means that the folder where the file is changed is a python package recognized by Python and will not be discussed in the future

Create app instruction

python manage.py startapp car
python manage.py startapp fruit

The system will automatically generate a basic structure of APP project structure:

    __init__.py
    admin.py
    apps.PY.py
    models.Py data table setting file is equivalent to m in MVC.py
    urls.Py creates its own files to control the API in the app. It can also be written directly in URLs of the fruitcar file.Py file.Py view file is equivalent to V in MVC,c

2、 Django life cycle

The life cycle of Django is as follows: user requests to initiate URL request → wsgiref module → Django middleware → Django (view URL corresponding function, model database interaction, HTML template rendering) → Django middleware → wsgiref module → user's page

The whole process from request to return is shown in the following figure:

Basic process principle of Python Django 01

3、 Django Middleware

middleware

Middleware is a framework level hook for handling requests and responses from Django,Used to change Django's inputs and outputs globally.

Five methods of Middleware

  1. process_ Request method
execution time parameter Return value Execution order
Before view function, before route matching The request object is the same object as the request parameter used in the view None: follow the normal process of httpresponse: then execute the current middleware and the previously executed middleware processes in reverse order_ The response method does not execute all other methods It is executed in the order of registration in midlist ware, which is the index value of this list
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
allow_url = ["/admin/", "/car/", "/fruit/"]


class Test2(MiddlewareMixin):
    def process_request(self, request):
        print("APIs that can be used to control requests, etc.")
        if request.path_info in allow_url:
            return
        else:
            return HttpResponse("This is httpresponse")
  1. process_ Response method
execution time parameter Return value Execution order
Final execution 1. Request: the request object, which is used in the view. 2. The request parameter is the same object. Response: the response object is the same object as the response returned in the view Response: this object must be returned and follow the normal process It is executed in reverse order of registration
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse


class Test(MiddlewareMixin):
    def process_request(self, request):
        print("This is a Middleware -- > request test")

    def process_response(self, request, response):
        print("Here is the httpresponse of the test")
        return HttpResponse("This is the httpresponse returned by the test")

process_ Request and process_ The execution process of response is as follows:

Basic process principle of Python Django 01

  1. process_ View method
execution time parameter Return value Execution order
In process_ After the request method and route match, before the view 1. Request: the request object, which is the same object as the request parameter used in the view. 2. view_ Func: the view function to be executed (it is the actual function object, not the name of the function as a string). 3. view_ Args: tuple of positional parameters to be passed to the view in the URL path. 4. view_ Kwargs: Dictionary of key value parameters to be passed to the view in the URL path 1. None: follow the normal process. 2. Httpresponse: the process of middleware after it_ View, and view does not execute, execute all middleware processes_ Response method Follow the order of registration
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse


class Test(MiddlewareMixin):
    def process_view(self, request, view_func, view_args, view_kwargs):
        ''
        print("This is the process of test_ View function“)
        print(view_func, type(view_func))

The execution process is as follows:

Basic process principle of Python Django 01

  1. process_ template_ Response method

Only when the object returned by the view function has a render () method (or indicates that the object is a templateresponse object or equivalent method)

execution time parameter Return value Execution order
After the view, process_ Before exception 1. Request: the request object, which is the same object as the request parameter used in the view. 2. Response: the templateresponse object (generated by view function or middleware) Response: this object must be returned and follow the normal process It is executed in reverse order of registration

middleware.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse


class Test(MiddlewareMixin):
    def process_request(self, request):
        print("This is a Middleware -- > test")

    def process_template_response(self, request, response):
        print("This is the process of test_ template_ response")

views.py

from django.shortcuts import render, HttpResponse, redirect


def index(request):
    print("This is the index page")
    rep = HttpResponse("This is the main page index")

    def render():
        print("Here is the render method in the index function")
        return HttpResponse("index")
    rep.render = render
    return rep
  1. process_ Exception method

Is executed only when an exception is triggered in the view

execution time parameter Return value Execution order
After the view, process_ Before response 1. Request: the request object, which is the same object as the request parameter used in the view. 2. Exception: exception object generated by view function exception 1. None: follow the normal process. The following: phttresponse is no longer executed_ Exception method It is executed in reverse order of registration

middlwware.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse


class Test(MiddlewareMixin):
    def process_request(self, request):
        print("This is a Middleware -- > test")

    def process_exception(self, request, exception):
        print("This is the process of test_ exception")
        print(exception)

views.py

from django.shortcuts import HttpResponse


def index(request):
    print("This is the index page")
    raise ValueError("This is an unsolicited error")
    return HttpResponse("This is the main page index")

The execution of the five middleware methods is shown in the figure below

Basic process principle of Python Django 01

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint

Recommended Today

HTML5 (V) geolocation

HTML5 Geolocation Locate the user The HTML5 geolocation API is used to get the user’s geographic location. Since this feature may infringe the privacy of users, the location information of users is not available unless they agree. be careful:Geolocation is more accurate for devices with GPS, such as the iPhone. geographyGeography; location; geo + location; […]