主頁 > 知識庫 > django免除csrf校驗(yàn)的方法

django免除csrf校驗(yàn)的方法

熱門標(biāo)簽:客戶服務(wù) 企業(yè)做大做強(qiáng) 語音系統(tǒng) 硅谷的囚徒呼叫中心 呼叫中心市場需求 百度AI接口 電話運(yùn)營中心 Win7旗艦版

免除csrf校驗(yàn)

在django中默認(rèn)啟動(dòng)csrf校驗(yàn),當(dāng)用戶發(fā)起post請求時(shí),必須攜帶csrf_token參數(shù)。如果不想使用csrf校驗(yàn)時(shí),可以使用以下方式免除校驗(yàn)。以下方式都是在局部中使用,如果想全局禁用時(shí),需要在settings文件中配置,這種方式不推薦使用。

一、函數(shù)免除csrf校驗(yàn)

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

二、對類免除csrf校驗(yàn)

第一種方式

# dispatch是類視圖的根方法,通過dispatch進(jìn)行反射找到其他請求

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"),
]

到此這篇關(guān)于django免除csrf校驗(yàn)的方法的文章就介紹到這了,更多相關(guān)django免除csrf校驗(yàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Django csrf校驗(yàn)的實(shí)現(xiàn)

標(biāo)簽:喀什 崇左 山西 濟(jì)南 山西 長沙 海南 安康

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《django免除csrf校驗(yàn)的方法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266