django免除csrf校驗的方法
在django中默認啟動csrf校驗,當(dāng)用戶發(fā)起post請求時,必須攜帶csrf_token參數(shù)。如果不想使用csrf校驗時,可以使用以下方式免除校驗。以下方式都是在局部中使用,如果想全局禁用時,需要在settings文件中配置,這種方式不推薦使用。
一、函數(shù)免除csrf校驗from django.views.decorators.csrf import csrf_exempt# 免除csrf校驗@csrf_exemptdef users(request): uses_list = ['柚子', '西瓜'] return HttpResponse(json.dumps(uses_list))二、對類免除csrf校驗第一種方式
# dispatch是類視圖的根方法,通過dispatch進行反射找到其他請求from django.views.decorators.csrf import csrf_exemptfrom django.utils.decorators import method_decoratorclass 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_exemptfrom 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_exemptclass 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_exempturlpatterns = [ path(’teachers/’, csrf_exempt(TeachersView.as_view()), name='teachers'),]
到此這篇關(guān)于django免除csrf校驗的方法的文章就介紹到這了,更多相關(guān)django免除csrf校驗內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 解決Python 進程池Pool中一些坑2. 三個不常見的 HTML5 實用新特性簡介3. Python獲取抖音關(guān)注列表封號賬號的實現(xiàn)代碼4. Python使用jupyter notebook查看ipynb文件過程解析5. ajax請求添加自定義header參數(shù)代碼6. python利用os模塊編寫文件復(fù)制功能——copy()函數(shù)用法7. Python如何讀寫CSV文件8. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究9. php測試程序運行速度和頁面執(zhí)行速度的代碼10. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁
