csrf中间件原理
django中间件最多有5种方法:
process_request
process_view
process_response
process_exception
process_render_template
csrf中间件写在process_view中,用户请求过来经过process_request,走到路由,再走process_view,走process_view之前判断这个视图函数或者类有没有设置csrf,如果设置了免除csrf验证,则跳过中间件的执行。
csrf全局关闭只需要注释中间件即可,但是局部如何免除csrf验证呢:
DBV:
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator # 当开启csrf中间件时,局部免除csrf验证 @csrf_exempt def bookcreate(request): pass # 当关闭csrf中间件时,局部开启csrf验证 @csrf_protect def publish(request): pass
CBV:
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator @method_decorator(csrf_exempt, name="dispatch") class BookView(views.View): def get(self, request): pass
原文地址:https://www.cnblogs.com/aizhinong/p/12563377.html
时间: 2024-11-05 22:22:56