• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

django免除csrf校验的方法

python 搞代码 4年前 (2022-01-09) 20次浏览 已收录 0个评论

免除csrf校验

在django中默认启动csrf校验来源gaodai#ma#com搞@代~码$网,当用户发起post请求时,必须携带csrf_token参数。如果不想使用csrf校验时,可以使用以下方式免除校验。以下方式都是在局部中使用,如果想全局禁用时,需要在settings文件中配置,这种方式不推荐使用。

一、函数免除csrf校验

from django.views.decorators.csrf import csrf_exempt# 免除csrf校验@csrf_exempt
def users(request):    
 uses_list = ["柚子", "西瓜"]    
 return HttpResponse(json.dumps(uses_list))

二、对类免除csrf校验

第一种方式

# dispatch是类视图的根方法,通过dispatch进行反射找到其他请求

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
class StudentsView(View):
    """student view"""
 @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        print("before")
        ret = super(StudentsView, self).dispatch(request, *args, **kwargs)
        print("after")
        return ret(request, *args, **kwargs)
    
    def get(self,*args,**kwargs):
        return HttpResponse("get")

    def post(self,*args,**kwargs):
        return HttpResponse("post")

    def put(self,*args,**kwargs):
        return HttpResponse("put")

    def delete(self,*args,**kwargs):
        return HttpResponse("delete")

第二种方式

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt,name="dispatch")
class StudentsView(View):
    """student view"""

    def get(self,*args,**kwargs):
        return HttpResponse("get")

第三种方式

from django.views.decorators.csrf import csrf_exempt
class MyBaseView(object):
    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        print("before")
        ret = super(MyBaseView, self).dispatch(request, *args, **kwargs)
        print("after")
        return ret

第四种,在url中添加

from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
    path('teachers/', csrf_exempt(TeachersView.as_view()), name="teachers"),
]

到此这篇关于django免除csrf校验的方法的文章就介绍到这了,更多相关django免除csrf校验内容请搜索搞代码以前的文章或继续浏览下面的相关文章希望大家以后多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:django免除csrf校验的方法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址