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设计】。

相关文章

从训练好的tensorflow模型中打印训练变量实例

从训练好的tensorflow模型中打印训练变量实例

从tensorflow 训练后保存的模型中打印训变量:使用tf.train.NewCheckpointReader() import tensorflow as tf reader...

Python读取properties配置文件操作示例

本文实例讲述了Python读取properties配置文件操作。分享给大家供大家参考,具体如下: 工作需要将Java项目的逻辑改为python执行,Java的很多配置文件都是.prope...

基于Python的ModbusTCP客户端实现详解

基于Python的ModbusTCP客户端实现详解

前言 Modbus协议是由Modicon公司(现在的施耐德电气Schneider Electric)推出,主要建立在物理串口、以太网TCP/IP层之上,目前已经成为工业领域通信协议的业界...

Python优化技巧之利用ctypes提高执行速度

首先给大家分享一个个人在使用python的ctypes调用c库的时候遇到的一个小坑 这次出问题的地方是一个C函数,返回值是malloc生成的字符串地址。平常使用也没问题,也用了有段时间,...

python实现超市商品销售管理系统

python实现超市商品销售管理系统

本文实例为大家分享了python超市商品销售管理系统的具体代码,供大家参考,具体内容如下 class Goods(object): def __init__(self, id, n...