Django 关于禁用 csrf 和 使用 csrf 操作
1. 基本使用
form表单中添加 {% csrf_token %}
2. 全站禁用
# 'django.middleware.csrf.CsrfViewMiddleware',
3. 局部禁用
'django.middleware.csrf.CsrfViewMiddleware',# 不注释 from django.views.decorators.csrf import csrf_exempt @csrf_exempt def csrf1(request): if request.method == 'GET': return render(request,'csrf1.html') else: return HttpResponse('ok')
4. 局部使用
# 'django.middleware.csrf.CsrfViewMiddleware', # 需要注释这一句话 from django.views.decorators.csrf import csrf_exempt,csrf_protect @csrf_protect def csrf1(request): if request.method == 'GET': return render(request,'csrf1.html') else: return HttpResponse('ok')
5. VIEW - CBV模式局部禁用
from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.shortcuts import render, HttpResponse from django.views import View class Cs(View): # @method_decorator(csrf_exempt) 建议用这个,具体原因后续再讲 @csrf_exempt def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return HttpResponse('GET,响应内容') def post(self, request, *args, **kwargs): return HttpResponse('Post,响应内容')
6. CBV 局部使用
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator from django.shortcuts import render, HttpResponse from django.views import View class Cs(View): # @method_decorator(csrf_exempt) @method_decorator(csrf_protect) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return HttpResponse('GET,响应内容') def post(self, request, *args, **kwargs): return HttpResponse('Post,响应内容')
7. 关于method_decorator的使用
Converts a function decorator into a method decorator. It can be used to decorate methods or classes; in the latter case, name is the name of the method to be decorated and is required.
name 这个参数是必备的,是为了装饰类中的get方法还是post方法。。。等等
from django.utils.decorators import method_decorator def test(func): # 装饰器 def inner(*args, **kwargs): print('hello,23232323') return func(*args, **kwargs) return inner @method_decorator(test, name='get') class Cs(View): # @method_decorator(csrf_exempt) # @method_decorator(csrf_protect) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return HttpResponse('GET,响应内容') def post(self, request, *args, **kwargs): return HttpResponse('Post,响应内容')
0顶
0 踩
共 0 条评论