csrf:跨站请求网站html
若是是ajax提交,能够按照下面的方式处理python
<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){jquery
}中执行函数ajax
$(function () { ajax_buttion() $.ajaxSetup() })
若是是form表单提交,则能够按照下面的方式处理django
<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的方式返回cookie
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默认是全局都生效的,可是若是咱们有需求,好比全局生效,可是我某个函数不须要使用csrf该怎么办;或者个人全局不设置csrf,可是对某个视图函数须要采用csrf,该怎么办app
这里就须要导入2个模块函数
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_protect
而后在视图函数中使用使用装饰器来装饰视图函数post
下面的例子就是起到全局启动csrf,可是我这个函数不启动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,可是我这个函数不启动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")