django的中间件是一个轻量级的插件系统,在django中的请求和响应中,可以利用中间件干预视图的请求和响应。
中间件是一个面向对象的类,有五个方法
process_request(self, request)
process_view(self, request, callback, callback_args,callback_kwargs)
process_template_response()
process_exception(self, request, exception)
process_response(self, request, response)
from django.utils.deprecation import MiddlewareMixin
class MiddleWareTest(MiddlewareMixin):
def process_request(self, request):
pass
案例—封杀某个ip地址
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse
class MiddleWareTest(MiddlewareMixin):
def process_request(self, request):
# 案例----封杀非法ip
print(request.META['REMOTE_ADDR']) # 获取访问的ip地址
req_ip = request.META['REMOTE_ADDR']
# 判断获取的ip
if req_ip == '10.10.107.33':
return HttpResponse('无法访问')
else:
print('正常访问')
python manage.py runserver 0.0.0.0:8000
## 对request携带的参数做预处理
## 例如参数中 是否含有敏感字等
def process_view(self,request, callback, callback_args, callback_kwargs):
# callback:对应的视图函数,访问的是哪个视图函数,callback就是那个函数
# callback_args:元组类型,视图函数的参数
# callback_kwargs:字典类型,视图函数的参数
print('我是在process_request函数执行完后执行的函数process_view')
def process_exception(self, request, exception):
import os
from Qshop.settings import BASE_DIR
print("我是 process_exception")
print(exception)
## 将exception写入文件中 error.log, 打开文件
file = os.path.join(BASE_DIR, 'error.log')
with open(file, "a") as f:
import time
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
content = "[%s]:%s\n" % (now, str(exception))
f.write(content)
return HttpResponse("代码报错了
%s " % exception)
def process_response(self, request, response):
print('我是响应对象')
return response
#---------------------------------中间件模板测试
def myprocess_tem_rep(request):
def test():
return HttpResponse('my test')
rep = HttpResponse('myprocee_tem_rep')
rep.render = test
return rep
路由:
middlewaretest.py
def process_response(self, request, response):
print('我是响应对象')
return response