一、简介

django为用户实现防止跨站请求伪造的功能,通过中间件 django.middleware.csrf.CsrfViewMiddleware 来完成。而对于django中设置防跨站请求伪造功能有分为全局和局部。

全局:

  中间件 django.middleware.csrf.CsrfViewMiddleware

局部:

@csrf_protect,为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件。
@csrf_exempt,取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件。
注:from django.views.decorators.csrf import csrf_exempt,csrf_protect

二、应用

1、普通表单

1
2
3
4
5
6
7
veiw中设置返回值:
  return render_to_response('Account/Login.html',data,context_instance=RequestContext(request))  
     或者
     return render(request, 'xxx.html', data)
  
html中设置Token:
  {% csrf_token %}

2、Ajax

对于传统的form,可以通过表单的方式将token再次发送到服务端,而对于ajax的话,使用如下方式。

view.py

1
2
3
4
5
6
7
8
9
10
from django.template.context import RequestContext
# Create your views here.
  
  
def test(request):
  
    if request.method == 'POST':
        print request.POST
        return HttpResponse('ok')
    return  render_to_response('app01/test.html',context_instance=RequestContext(request))

text.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    {% csrf_token %}
  
    <input type="button" onclick="Do();"  value="Do it"/>
  
    <script src="/static/plugin/jquery/jquery-1.8.0.js"></script>
    <script src="/static/plugin/jquery/jquery.cookie.js"></script>
    <script type="text/javascript">
        var csrftoken = $.cookie('csrftoken');
  
        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });
        function Do(){
  
            $.ajax({
                url:"/app01/test/",
                data:{id:1},
                type:'POST',
                success:function(data){
                    console.log(data);
                }
            });
  
        }
    </script>
</body>
</html>

更多:https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

原文地址:https://www.cnblogs.com/wupeiqi/articles/5246483.html

pythonのdjango CSRF简单使用的更多相关文章

  1. Python django实现简单的邮件系统发送邮件功能

    Python django实现简单的邮件系统发送邮件功能 本文实例讲述了Python django实现简单的邮件系统发送邮件功能. django邮件系统 Django发送邮件官方中文文档 总结如下: ...

  2. Python Django 实现简单注册功能

    Python Django 实现简单注册功能 项目创建略,可参考前期文档介绍. 目录结构如下 编辑views.py from django.shortcuts import render # Crea ...

  3. Python Django 之 简单入门

    一.下载Django并安装 1.下载Django 2.安装 二.新建Django project 1.使用django-admin新建mysite 项目 django-admin startproje ...

  4. pythonのdjango Form简单应用。

    Form表单有两种应用场景: 1.生成HTML标签. 2.验证输入内容. 如果我们在django程序中使用form时,需要在views中导入form模块 from django import form ...

  5. python, Django csrf token的问题

    环境 Window 7 Python2.7 Django1.4.1 sqlite3 问题 在使用Django搭建好测试环境后,写了一个提交POST表单提交留言的测试页面. 如图: 填写表单,点击“提交 ...

  6. python - Django - restframework 简单使用 和 组件

    FBV 和 CBV CBV 通过函数调用方法FBV 通过类调用方法    其本质上都是 CBV 但是 FBV 内部封装了关于 method 的方法,由于基本上都是前端的请求,所有像GET,POST等方 ...

  7. Python - Django - CSRF

    CSRF 攻击: 把 settings.py 中的 csrf 注释掉 正规网站: 创建修改密码页面 password.html: <!DOCTYPE html> <html lang ...

  8. Python - Django - Cookie 简单用法

    home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...

  9. RSA算法在Python Django中的简单应用

    说明 RSA算法是当今使用最广泛,安全度最高的加密算法. • RSA算法的安全性理论基础 [引]根据百科介绍,对极大整数做因数分解的难度决定了RSA算法的可靠性.换言之,对一极大整数做因数分解愈困难, ...

随机推荐

  1. sql server 压缩数据库

    收缩日志 ALTER DATABASE 数据库名称 SET RECOVERY SIMPLEDBCC SHRINKDATABASE(数据库名称, 0) 压缩数据库ALTER DATABASE 数据库名称 ...

  2. Spring Security(三十):9.5 Access-Control (Authorization) in Spring Security

    The main interface responsible for making access-control decisions in Spring Security is the AccessD ...

  3. python小白——进阶之路——day3天-———容器类型数据+Number类型强制类型转换

    -->Number 部分 int :     整型   浮点型 布尔类型  纯数字字符串 float:    整型   浮点型 布尔类型  纯数字字符串 complex:  整型   浮点型 布 ...

  4. js 对日期处理

    // 对Date的扩展,将 Date 转化为指定格式的String // 月(M).日(d).小时(h).分(m).秒(s).季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 个占 ...

  5. python中的数组和列表

    ####转自:模式识别实验室主任   #环境win64+anaconda+python3.6 list & array (1)list不具有array的全部属性(如维度.转置等) 代码1: # ...

  6. springboot maven 报错ArtifactDescriptorException

    maven具体报错提示如下: Description Resource Path Location TypeArtifactDescriptorException: Failed to read ar ...

  7. git 版本管控 发布

    https://www.cnblogs.com/charlesblc/p/6051569.html http://www.ruanyifeng.com/blog/2012/07/git.html 1. ...

  8. vue.js实战——计算属性

    1set和get: 注意: this.lastName=names[names.length-1];//解决连续输入空格后lastName消失的问题 练习代码如下: <!DOCTYPE html ...

  9. MyBatis的接口式编程Demo

    很久没细看过MyBatis了,时间一长就容易忘记. 下面是一个接口式编程的例子. 这里的例子一共分为4步: 1 首先要有一个namespace为接口的全类名的映射文件,该例中是 IMyUser.xml ...

  10. 纯css实现checkbox开关切换按钮

    我们都知道 checkbox 标签默认样式 实在是太low了,故对CheckBox美化很有必要. 现提供两种方式对其进行美化. 方法一 <div class="switch-wrap ...