django免除csrf校驗的方法
更新時間:2021年05月10日 10:13:26 作者:一個正經(jīng)程序員
這篇文章主要介紹了django免除csrf校驗的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
免除csrf校驗
在django中默認啟動csrf校驗,當用戶發(fā)起post請求時,必須攜帶csrf_token參數(shù)。如果不想使用csrf校驗時,可以使用以下方式免除校驗。以下方式都是在局部中使用,如果想全局禁用時,需要在settings文件中配置,這種方式不推薦使用。
一、函數(shù)免除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校驗內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關文章
python智聯(lián)招聘爬蟲并導入到excel代碼實例
這篇文章主要介紹了python智聯(lián)招聘爬蟲并導入到excel代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09
Python字符和字符值(ASCII或Unicode碼值)轉換方法
這篇文章主要介紹了Python字符和字符值(ASCII或Unicode碼值)轉換方法,即把字符串在ASCII值或者Unicode值之間相與轉換的方法,需要的朋友可以參考下2015-05-05
PySide(PyQt)使用QPropertyAnimation制作動態(tài)界面的示例代碼
文章介紹了如何使用PySide或PyQt的QPropertyAnimation類來創(chuàng)建動態(tài)界面效果,感興趣的朋友一起看看吧2025-03-03

