django的csrf实现过程详解

yipeiwu_com6年前Python基础

如果是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){

}中执行函数

$(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默认是全局都生效的,但是如果我们有需求,比如全局生效,但是我某个函数不需要使用csrf该怎么办;或者我的全局不设置csrf,但是对某个视图函数需要采用csrf,该怎么办

这里就需要导入2个模块

from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.csrf import csrf_protect

然后在视图函数中使用使用装饰器来装饰视图函数

下面的例子就是起到全局启动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")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Python的Django框架中获取单个对象数据的简单方法

相对列表来说,有些时候我们更需要获取单个的对象, `` get()`` 方法就是在此时使用的: >>> Publisher.objects.get(name="Ap...

使用python为mysql实现restful接口

最近在做游戏服务分层的时候,一直想把mysql的访问独立成一个单独的服务DBGate,原因如下: 请求收拢到DBGate,可以使DBGate变为无状态的,方便横向扩展 当请求量或者存储量...

python实现用类读取文件数据并计算矩形面积

python实现用类读取文件数据并计算矩形面积

1.创建一个类Rectangle,已知a、b求面积,求三角形的面积 2.结合题目一,从题目一文件中读取数据,并采用类的方法,将计算的结果写在另一个文档中。 (1)利用类进行计算一个矩形的...

举例讲解Python程序与系统shell交互的方式

概述 考虑这样一个问题,有hello.py脚本,输出”hello, world!”;有TestInput.py脚本,等待用户输入,然后打印用户输入的数据。那么,怎么样把hello.py输...

python多维数组切片方法

1、数组a第0个元素(二维数组)下的所有子元素(一维数组)的第一列 import numpy as np b=np.arange(24) a=b.reshape(2,3,4) pri...