django的csrf實現(xiàn)過程詳解
如果是ajax提交,可以按照下面的方式處理
<script src="/static/jq/jquery-3.3.1.js"></script>
<script src="/static/jq/jquery.cookie.js"></script>
<script>
$(function () {
ajax_buttion()
})
function ajax_buttion() {
$("#btn").bind("click",function () {
$.ajax(
{
url:"/test/app1/",
type:"post",
data:{
username:"root",
pwd:"admin"
},
headers:{
"X-CSRFToken":$.cookie("csrftoken")
},
sucess:function (data) {
console.log(data)
}
}
)
})
}
</script>
可以設置一個全局的設置,然后在$(function){
}中執(zhí)行函數(shù)

$(function () {
ajax_buttion()
$.ajaxSetup()
})
如果是form表單提交,則可以按照下面的方式處理
<form action="/test/app1/" method="post">
{% csrf_token %}
<input type="text" name="uname">
<input type="submit" value="submit">
<input type="button" value="ajax" id="btn">
</form>
然后返回使用render的方式返回
def test(request):
# int("hahah")
# print(settings.C)
print("test------->views",time.time())
print(request.method)
print("_".center(100,"-"))
print(request)
# return HttpResponse("last_app1")
return render(request,"test.html")
中間件里csrf默認是全局都生效的,但是如果我們有需求,比如全局生效,但是我某個函數(shù)不需要使用csrf該怎么辦;或者我的全局不設置csrf,但是對某個視圖函數(shù)需要采用csrf,該怎么辦
這里就需要導入2個模塊
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_protect
然后在視圖函數(shù)中使用使用裝飾器來裝飾視圖函數(shù)
下面的例子就是起到全局啟動csrf,但是我這個函數(shù)不啟動csrf
@csrf_exempt
def test(request):
# int("hahah")
# print(settings.C)
print("test------->views",time.time())
print(request.method)
print("_".center(100,"-"))
print(request)
# return HttpResponse("last_app1")
return render(request,"test.html")
下面的例子就是全局不啟用csrf,但是我這個函數(shù)不啟動csrf
@csrf_protect
def test(request):
# int("hahah")
# print(settings.C)
print("test------->views",time.time())
print(request.method)
print("_".center(100,"-"))
print(request)
# return HttpResponse("last_app1")
return render(request,"test.html")
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python面向對象實現(xiàn)名片管理系統(tǒng)文件版
這篇文章主要為大家詳細介紹了python面向對象實現(xiàn)名片管理系統(tǒng)文件版,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04
python中超簡單的字符分割算法記錄(車牌識別、儀表識別等)
這篇文章主要給大家介紹了關于python中超簡單的字符分割算法記錄,如車牌識別、儀表識別等,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2021-09-09
對python3 sort sorted 函數(shù)的應用詳解
今天小編就為大家分享一篇對python3 sort sorted 函數(shù)的應用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06

