middleware middleware

middleware

middle key

Middleware in Django is a lightweight, low-level plug-in system that can intervene in Django's request and response processing and modify Django's input or output

The design of middleware provides developers with a non-intrusive development method and enhances the robustness of the Django framework. Other MVC frameworks also have this function, named IOC

Django presets six methods in middleware. The difference between these six methods is that they are executed in different stages and intervene in input or output. The methods are as follows

1. Initialization: without any parameters, it is called once when the server responds to the first request to determine whether to enable the current middleware

1
2
def  __init__():
     pass

2. Before processing the request: called on each request, returning None or an HttpResponse object

1
2
def  process_request(request):
     pass

  

3. Before processing the view: called on each request, returning None or the HttpResponse object

1
2
def  process_view(request, view_func, view_args, view_kwargs):
     pass

4. Before processing the template response: called on each request, returning a response object that implements the render method

1
2
def  process_template_response(request, response):
     pass

5. After the response is processed: called before all responses are returned to the browser, called on each request, returning an HttpResponse object

1
2
def  process_response(request, response):
     pass

6. Exception handling: called when the view throws an exception, called on each request, and returns an HttpResponse object

1
2
def  process_exception(request,exception):
     pass

  

Example

  • Middleware is a separate python class that can define one or more of these five methods
  • Create the middleware.py file in the booktest/ directory with the following code:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class  my_mid:
         def  __init__( self ):
             print  '--------------init'
         def  process_request( self ,request):
             print  '--------------request'
         def  process_view( self ,request, view_func, view_args, view_kwargs):
             print  '--------------view'
         def  process_template_response( self ,request, response):
             print  '--------------template'
             return  response
         def  process_response( self ,request, response):
             print  '--------------response'
             return  response
 

In the test5/settings.py file, register with the MIDDLEWARE_CLASSES item:

Modify the view index in booktest/views.py

def index(request):
    print '======index======'
    return render(request,'booktest/index.html')

 

Run the server, the effect on the command line is as follows:

Refresh the page, the effect on the command line is as follows:

exception middleware

Define two exception classes in booktest/middleware.py as follows:

class exp1:
    def process_exception(self,request,exception):
        print '--------------exp1'
class exp2:
    def process_exception(self,request,exception):
        print '--------------exp2'

In the test5/settings.py file, register with the MIDDLEWARE_CLASSES item

 

Modify the view index in booktest/views.py:

1
2
3
4
def  index(request):
     print  '======index======'
     raise  Exception( '自定义异常' )
     return  render(request, 'booktest/index.html' )

  

Summarize:

The intermediate key can interfere with the bottom layer of djiango. If you want to not write the same code repeatedly, you can consider using the intermediate key. Django actually encapsulates a lot of intermediate keys. For example, when the form is submitted, if we add {%csrf_token%} A default hidden domain will be generated and set to the browser, a cookie information.

middle key

Middleware in Django is a lightweight, low-level plug-in system that can intervene in Django's request and response processing and modify Django's input or output

The design of middleware provides developers with a non-intrusive development method and enhances the robustness of the Django framework. Other MVC frameworks also have this function, named IOC

Django presets six methods in middleware. The difference between these six methods is that they are executed in different stages and intervene in input or output. The methods are as follows

1. Initialization: without any parameters, it is called once when the server responds to the first request to determine whether to enable the current middleware

1
2
def  __init__():
     pass

2. Before processing the request: called on each request, returning None or an HttpResponse object

1
2
def  process_request(request):
     pass

  

3. Before processing the view: called on each request, returning None or the HttpResponse object

1
2
def  process_view(request, view_func, view_args, view_kwargs):
     pass

4. Before processing the template response: called on each request, returning a response object that implements the render method

1
2
def  process_template_response(request, response):
     pass

5. After the response is processed: called before all responses are returned to the browser, called on each request, returning an HttpResponse object

1
2
def  process_response(request, response):
     pass

6. Exception handling: called when the view throws an exception, called on each request, and returns an HttpResponse object

1
2
def  process_exception(request,exception):
     pass

  

Example

  • Middleware is a separate python class that can define one or more of these five methods
  • Create the middleware.py file in the booktest/ directory with the following code:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class  my_mid:
         def  __init__( self ):
             print  '--------------init'
         def  process_request( self ,request):
             print  '--------------request'
         def  process_view( self ,request, view_func, view_args, view_kwargs):
             print  '--------------view'
         def  process_template_response( self ,request, response):
             print  '--------------template'
             return  response
         def  process_response( self ,request, response):
             print  '--------------response'
             return  response
 

In the test5/settings.py file, register with the MIDDLEWARE_CLASSES item:

Modify the view index in booktest/views.py

def index(request):
    print '======index======'
    return render(request,'booktest/index.html')

 

运行服务器,命令行中效果如下图:

刷新页面,命令行中效果如下图:

异常中间件

在booktest/middleware.py中定义两个异常类如下:

class exp1:
    def process_exception(self,request,exception):
        print '--------------exp1'
class exp2:
    def process_exception(self,request,exception):
        print '--------------exp2'

在test5/settings.py文件中,向MIDDLEWARE_CLASSES项中注册

 

修改booktest/views.py中视图index:

1
2
3
4
def  index(request):
     print  '======index======'
     raise  Exception( '自定义异常' )
     return  render(request, 'booktest/index.html' )

  

总结:

中间键可以干预djiango的底层,如果想要不重复编写相同的代码,可考虑使用中间键,django其实就是封装了好多中间键,如,在表单提交的时候,如果我们添加了{%csrf_token%}就会生成一个默认的隐藏域,并向浏览器设值了,一个cookie信息。

Guess you like

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