middleware (中间件)

是一个完整socket请求过程中必须经过的步骤 客户端发起request--->中间件request--->views处理--->中间件response--->客户端
如果在中间件中请求出错,则直接返回响应
作用:可以对所有请求做统一操作,也可以进行过滤

中间件的5个方法:
process_request
process_view
process_exception
process_exception
process_template_response
# 接收请求后首先经过process_request
def process_request(self, request):
  print('请求1')
  pass

# 当process_request处理完后,进行路由映射,再返回第一条继续进行处理
def process_view(self, request, callback, callback_args, callback_kwargs):
  pass

# 当views处理完,且其中有错时,就会自动调用此方法,可返回给页面错误信息(没有错就不执行)(执行顺序是倒序,\
# 但如果和views最近的没有进行处理则往上查,查到后处理并返回最后一条进行process_response)
def process_exception(self, request, exception):
return HttpResponse('页面出错了!!!')

# 当views处理完成之后倒序的进行返回,所以必须要有return response
def process_response(self, request, response):
return response

# 如若views返回的内容中有render方法,则会执行
def process_template_response(self, request, response):
 

MIDDLEWARE = [
    # 'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'Middle.m1.Row1',
    'Middle.m1.Row2',
    'Middle.m1.Row3',
    # 'django.middleware.cache.FetchFromCacheMiddleware',
]
settings.py
from django.middleware.csrf import CsrfViewMiddleware
from django.shortcuts import render,HttpResponse

# from sg import pizza_done
# pizza_done.send(sender='seven',toppings=123, size=456)  # 写在需要触发的位置


class Row1(CsrfViewMiddleware):
    def process_request(self, request):
        pass
        print('请求...1')
    def process_view(self, request, callback, callback_args, callback_kwargs):
        # pass
        print('请求...4')
    def process_response(self, request, response):
        print('响应3')
        return response
class Row2(CsrfViewMiddleware):
    def process_request(self, request):
        # pass
        print('请求...2')
    def process_view(self, request, callback, callback_args, callback_kwargs):
        # pass
        print('请求...5')
    def process_response(self, request, response):
        print('响应2')
        return response
class Row3(CsrfViewMiddleware):
    def process_request(self, request):
        # pass
        print('请求...3')
    def process_view(self, request, callback, callback_args, callback_kwargs):
        # pass
        print('请求...6')
    def process_response(self, request, response):
        print('响应1')
        return response
    def process_exception(self, request, exception):
        # pass
        print(exception)
        return HttpResponse(exception)
m1.py

 


 posted on 2018-08-24 13:58  ._东汕再  阅读(125)  评论(0编辑  收藏  举报