CSRF # 表示django全局發送post請求均需要字符串驗證
功能:防止跨站請求偽造的功能
工作原理:客戶端訪問服務器端,在服務器端正常返回給客戶端數據的時候,而外返回給客戶端一段字符串,等到客戶端下次訪問服務器
端時,服務器端會到客戶端查找先前返回的字符串,如果找到則繼續,找不到就拒絕。
訪問流程:客戶端-》URL路由系統 - 》 CSRF -》視圖函數
需要在客戶端頁面的post表單內添加:{% csrf_token %}
全局生效:
中間件 django.middleware.csrf.CsrfViewMiddleware
局部生效:
@csrf_protect,為當前函數強制設置防跨站請求偽造功能,即便settings中沒有設置全局中間件。
@csrf_exempt,取消當前函數防跨站請求偽造功能,即便settings中設置了全局中間件。
寫法如下:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_exempt
def index(request): # 這樣表示此函數取消CSRF驗證
實例:登錄頁面通過ajax進行form表單提交

<body> <div class="container"> <form id='logfrom' class="form-signin"> {% csrf_token %} <h2 class="form-signin-heading">主機管理頁面</h2> <label for="inputusername" class="sr-only">用戶名</label> <input type="text" id="inputusername" class="form-control" name="uname" placeholder="username" required="" autofocus=""><span class="nameinfo hide">用戶名錯誤</span> <label for="inputPassword" class="sr-only">密碼</label> <input type="password" id="inputPassword" class="form-control" name="upwd" placeholder="Password" required=""><span class="pwdinfo hide">密碼錯誤</span> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> Remember me </label> </div> <input id='login' class="btn btn-lg btn-primary btn-block" type="button" value="登錄"> </form> </div> <!-- /container --> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="/static/ie10-viewport-bug-workaround.js"></script> <script src="/static/jquery-1.12.4.min.js"></script> <script src="static/jquery-cookie/jquery.cookie.js"></script> <script> $('#login').click(function () { //以下的ajaxSetup為全局的csrf設置 $.ajaxSetup({ // xhr為XmlHttpRequest 對象,是一個固定寫法 beforeSend: function (xhr, settings) { /*這里settings代表下面將要執行的ajax里面的內容*/ // 以下表示設置請求頭 xhr.setRequestHeader('X-CSRFtoken', $.cookie('csrftoken')) } }); $.ajax({ url:'/index', type:'post', data:{'logname':$('#inputusername').val(),'logpwd':$('#inputPassword').val()}, success:function (data) { if (data == 'ok'){ location.href = '/index' }if(data == 'nmerr'){ $('.nameinfo').removeClass('hide'); }if(data =='pwderr'){ $('.pwdinfo').removeClass('hide'); } } }) }) </script> </body>
views函數中對應的函數設置
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_exempt
def index(request):
........
中間件
可以定義5個方法:
- process_request
- process_view
- process_response
- process_exception # 做異常處理
- process_template_response # 了解即可,如果views中的函數返回的對象中具有render方法,才執行這個函數
適合對所有的請求做統一操作,(如:黑名單)
游覽器-URL -中間件-視圖函數
實例如:
settings的MIDDLEWARE配置:
'middle.MIDDLE.M1',
'middle.MIDDLE.M2',
'middle.MIDDLE.M3',
模塊MIDDLE文件內容

from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse class M1(MiddlewareMixin): def process_request(self,request): print('中間件1') def process_view(self,request,view_func,view_func_args,view_func_kwargs): ''' :param request: 請求數據 :param view_func: 視圖函數 :param view_func_args: 視圖函數參數 :param view_func_kwargs: 視圖函數參數 :return: ''' print('新添加中間件1') def process_response(self,request,response): print('中間件返回1') return response def process_exception(self,request,exception): ''' 當執行的視圖函數運行出現錯誤,則執行此方法提示''' if isinstance(exception,ValueError): return HttpResponse('當前的view函數出現了異常,請檢查') def process_template_response(self, request, response): # 如果試圖函數views中的函數返回的對象中,具有render方法,才執行 pass return response class M2(MiddlewareMixin): def process_request(self,request): print('中間件2') def process_view(self,request,view_func,view_func_args,view_func_kwargs): print('新添加中間件2') def process_response(self, request, response): print('中間件返回2') return response class M3(MiddlewareMixin): def process_request(self,request): print('中間件3') def process_view(self,request,view_func,view_func_args,view_func_kwargs): print('新添加中間件3') def process_response(self, request, response): print('中間件返回3') return response
請求流程:訪問-》M1.process_request -> M2.process_request -> M3.process_request -> 返回
M1.process_view -> M2.process_view -> M3.process_view -> 視圖函數 -> M3.process_response->M2.process_response->M1.process_response