定义:
编写中间件:
注册中间件:
添加中间件:
1.在项目目录下添加一个文件夹(名字随意),然后文件夹下创建.py文件
2.将中间件添加到setting文件中
python
MIDDLEWARE = [
'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',
'middleware.mymiddleware.MyMW',
]
3..py文件下编写中间件
python
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse
class MyMW(MiddlewareMixin):
def process_request(self, request):
print('请求之前')
return None
def process_view(self, request, view_func, view_args, view_kwargs):
print('视图函数之前')
return None
def process_response(self, request, response):
print('响应之后')
return response
CSRF-跨站伪造请求攻击
CSRF防范:
防范步骤: