django免除csrf校驗(yàn)的方法
在django中默認(rèn)啟動(dòng)csrf校驗(yàn),當(dāng)用戶(hù)發(fā)起post請(qǐng)求時(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_exemptdef users(request): uses_list = ['柚子', '西瓜'] return HttpResponse(json.dumps(uses_list))二、對(duì)類(lèi)免除csrf校驗(yàn)第一種方式
# dispatch是類(lèi)視圖的根方法,通過(guò)dispatch進(jìn)行反射找到其他請(qǐng)求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校驗(yàn)的方法的文章就介紹到這了,更多相關(guān)django免除csrf校驗(yàn)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算2. HTML <!DOCTYPE> 標(biāo)簽3. JS圖片懶加載庫(kù)VueLazyLoad詳解4. Java實(shí)現(xiàn)的迷宮游戲5. Java利用TCP協(xié)議實(shí)現(xiàn)客戶(hù)端與服務(wù)器通信(附通信源碼)6. Java實(shí)現(xiàn)UDP通信過(guò)程實(shí)例分析【服務(wù)器端與客戶(hù)端】7. Vue基于iview table展示圖片實(shí)現(xiàn)點(diǎn)擊放大8. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶(hù)登錄的步驟9. Java PreparedStatement用法詳解10. Python 解決火狐瀏覽器不彈出下載框直接下載的問(wèn)題

網(wǎng)公網(wǎng)安備