Django关于禁用csrf和使用csrf操作

本文和大家分享的是django中关于禁用csrf和使用csrf操作相关内容,一起来看看吧,希望对大家 学习django 有所帮助。
  1. 基本使用
  form表单中添加
  {% csrf_token %}
  2. 全站禁用
  # 'django.middleware.csrf.CsrfViewMiddleware',
  3. 局部禁用
  'django.middleware.csrf.CsrfViewMiddleware',# 不注释
  from django.views.decorators.csrf import csrf_exempt
  @csrf_exemptdef 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_protectdef csrf1(request):
  if request.method == 'GET':
  return render(request,'csrf1.html')
  else:
  return HttpResponse('ok')
  5. 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 Viewclass 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 Viewclass 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_decoratordef 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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值