首页 > 代码库 > python EasyUI + Django--整合 CSRF 防护去除

python EasyUI + Django--整合 CSRF 防护去除

先来张完整图:

                技术分享

                                       关于Django 得CSRF  中间件      防护   GET 是不做CSRF验证得   但POST 默认验证  $.cookie(‘csrftoken‘))    "value"

 

 

   第一种方法:   在主配置文件   settings.py  中去除中间件

           技术分享

       第二种:   无需 注销 第一种方法     #‘django.middleware.csrf.CsrfViewMiddleware‘,

 

     在Views.py 中引入   from django.views.decorators.csrf import  csrf_exempt ,csrf_protect


                                      在需要得方法前添加   @csrf_exempt 不启用CSRF               反之 @csrf_protect 


第三种: 通过CSRF 验证 FORM 表单 加入{% csrf_token %}

ajax通过CSRF验证:
                 
$.ajax({
    url: ‘/remove/‘,
    type: ‘POST‘,
    data: {id:row.id},
    headers: {‘X-CSRFtoken‘: $.cookie(‘csrftoken‘)},  

           定义全局ajax     headers请求头 CSRF验证

        $(function (){
            $.ajaxSettings({
                beforeSend: function(xhr,settings){
                    xhr.setRequestHeader(‘X-CSRFtoken‘, $.cookie(‘csrftoken‘))
                }
            })
        });

  

 

models 表结构代码

             

from django.db import models
#根据类对象生成表结构
#python manage.py makemigrations
#根据表结构生成对应数据库表 SQLite
#python manage.py migrate
class Person(models.Model):
    Uesr_name = models.CharField(max_length=32)
    User_sex = models.CharField(max_length=32, null=True,blank=True)
    User_phone=models.IntegerField(max_length=255, null=True,blank=True)
    User_addre=models.CharField(max_length=32, null=True,blank=True)

  

urls.py   URL代码

from django.conf.urls import url
from django.contrib import admin
from App.views import *
urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^$,indexl),
    url(r^start/,  app_start),
     url(r^read/,  Read_all_SQL),
    url(r^edit/(?P<id>\d+), Edit_UserNmae),
    url(r^remove/, Remove_US_ID),
]

 

app.views    Views 代码

# -*- coding: utf-8 -*-
from django.views.decorators.csrf import  csrf_exempt ,csrf_protect
from django.shortcuts import render ,HttpResponse ,HttpResponseRedirect
import models ,json
import sys
reload(sys)
# Create your views here.
#indexl  &
def indexl(request):
    return HttpResponseRedirect("http://127.0.0.1:8000/start/")

#Read all SQLite Data
@csrf_exempt
def Read_all_SQL(request):
    obj_all=models.Person.objects.all()
    eaList=[]
    for li in obj_all:
        eaList.append({"firstname" : li.Uesr_name , "lastname" : li.User_sex , "phone": li.User_phone , "email" : li.User_addre,"id" : li.id})
    eaList_len=json.dumps(len(eaList))
    json_data_list = {‘rows‘:eaList,‘total‘:eaList_len}
    easyList=json.dumps(json_data_list)
    return HttpResponse(easyList)

#Edit_UserName
@csrf_exempt
def Edit_UserNmae(request,id):
    print(id)
    print(request.method)
    if request.method == ‘POST‘:
        Uesr_name=request.POST.get(‘firstname‘)
        User_sex=request.POST.get(‘lastname‘)
        User_phone=request.POST.get(‘phone‘)
        User_addre=request.POST.get(‘email‘)
        dic={‘Uesr_name‘: Uesr_name ,‘User_sex‘ : User_sex ,
         ‘User_phone‘ : User_phone , ‘User_addre‘ : User_addre};
        models.Person.objects.filter(id=id)            .update(**dic)
        return HttpResponse("Edit_OK")

#add User_Name  + start_app
def app_start(request):
    # add_save_user
    if request.method=="POST":
        print("POST")
        print(request.POST)
        Uesr_name=request.POST.get(‘firstname‘)
        User_sex=request.POST.get(‘lastname‘)
        User_phone=request.POST.get(‘phone‘)
        User_addre=request.POST.get(‘email‘)
        dic={‘Uesr_name‘: Uesr_name ,‘User_sex‘ : User_sex ,
         ‘User_phone‘ : User_phone , ‘User_addre‘ : User_addre};
        models.Person.objects.create(**dic)
        return HttpResponse("save")
    else:
         print(" is null_!")
    return render(request,‘app/index_bak.html‘)

#Remove SQL_ID
@csrf_exempt
def Remove_US_ID(request):
    if request.method=="POST":
        print("REMOVE POST")
        print(request.POST.get(‘id‘))
        us_id=request.POST.get(‘id‘)
        models.Person.objects.filter(id=us_id).delete()
    return HttpResponse("REMOVE")

  

 

templates.app.index.html 代码        html 代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EasyUI框架</title>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/static/jquery/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/static/jquery/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/static/jquery/themes/color.css">
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/static/jquery/demo/demo.css">
<script type="text/javascript" src="http://www.mamicode.com/static/jquery/jquery.min.js"></script>
<script type="text/javascript" src="http://www.mamicode.com/static/jquery/jquery.easyui.min.js"></script>
</head>
<body>
<h2>前端_EasyUI框架—后端_Django--整合</h2>
<p>QQ_237356573 (增 删 改 查)</p>

<table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
url="/read/"
toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="firstname" width="50">Name</th>
<th field="lastname" width="50">SEX</th>
<th field="phone" width="50">Phone</th>
<th field="email" width="50">OWE</th>
</tr>
</thead>
</table>
<div id="toolbar">
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">Remove User</a>
</div>

<div id="dlg" class="easyui-dialog" style="width:400px"
closed="true" buttons="#dlg-buttons">
<form id="fm" method="post" novalidate style="margin:0;padding:20px 50px">
<div style="margin-bottom:20px;font-size:14px;border-bottom:1px solid #ccc">add User_name</div>
<div style="margin-bottom:10px">
<input name="firstname" class="easyui-textbox" required="true" label="Name:" style="width:100%">
</div>
<div style="margin-bottom:10px">
<input name="lastname" class="easyui-textbox" required="true" label="sex:" style="width:100%">
</div>
<div style="margin-bottom:10px">
<input name="phone" class="easyui-textbox" required="true" label="Phone:" style="width:100%">
</div>
<div style="margin-bottom:10px">
<input name="email" class="easyui-textbox" required="true" label="OWE:" style="width:100%">
</div>
</form>
</div>
<div id="dlg-buttons">
<a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveUser()" style="width:90px">Save</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$(‘#dlg‘).dialog(‘close‘)" style="width:90px">Cancel</a>
</div>
<script type="text/javascript">
//设置ajax全局Header 请求头$.cookie(‘csrftoken‘)
$(function (){
$.ajaxSettings({
beforeSend: function(xhr,settings){
xhr.setRequestHeader(‘X-CSRFtoken‘, $.cookie(‘csrftoken‘))
}
})
});


var url;
// 显示 编辑框
function newUser(){
$(‘#dlg‘).dialog(‘open‘).dialog(‘center‘).dialog(‘创建‘,‘New User‘);
$(‘#fm‘).form(‘clear‘);
url = ‘/start/‘;
}

//编辑 USER
function editUser(){
var row = $(‘#dg‘).datagrid(‘getSelected‘);
if (row){
$(‘#dlg‘).dialog(‘open‘).dialog(‘center‘).dialog(‘setTitle‘,‘Edit User‘);
$(‘#fm‘).form(‘load‘,row);
// ajax 编辑USER 并且 通过ajax 保存到后端 SQL
url = ‘/edit/‘+row.id;
}
}

// 创建——USER 并 SAVE 保存
function saveUser(){
$(‘#fm‘).form(‘submit‘,{
url: url,
onSubmit: function(){
return $(this).form(‘validate‘);
},
success: function(result){
if (result=="save"){
$(‘#dlg‘).dialog(‘close‘);
$(‘#dg‘).datagrid(‘reload‘);
}else
if (result.errorMsg){
$.messager.show({
title: ‘Error‘,
msg: result.errorMsg
});
} else {
$(‘#dlg‘).dialog(‘close‘); // close the dialog
$(‘#dg‘).datagrid(‘reload‘); // reload the user data
}
}
});
}

// 根据ID 删除 user
function destroyUser(){
var row = $(‘#dg‘).datagrid(‘getSelected‘);
if (row){
$.messager.confirm(‘Confirm‘,‘Are you sure you want to destroy this user?‘,function(r){
if (r){
$.ajax({
url: ‘/remove/‘,
type: ‘POST‘,
data: {id:row.id},
headers: {‘X-CSRFtoken‘: $.cookie(‘csrftoken‘)},
success: function(data) {
if (datahttp://www.mamicode.com/=="REMOVE"){
$(‘#dg‘).datagrid(‘reload‘); // reload the user data
}
},
error: function(data) {
alert("error")
}
});
}
});
}
}
</script>
</body>
</html>

  

new_user

技术分享

Edit_user

技术分享

 

Remove_user

技术分享

 

源码下载地址  :https://pan.baidu.com/s/1c25jBwc

python EasyUI + Django--整合 CSRF 防护去除