中间件是一个用来处理Django的请求和响应的框架级别的钩子,用于在全局范围内改变Django的输入和输出,只要是全局相关的功能都应该考虑使用Django中间件来完成html
中间件在settings配置文件中web
from django.middleware.security import SecurityMiddleware # 查看某个中间件代码方式,直接复制上去用from...import... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
中间件干了什么事?ajax
请求来时由Django中间件默认的七个关口进行校验,当任意一个校验不经过都会返回,当七个默认关口都校验成功后,判断是否是第一次请求,若是不是,会直接去缓存数据库中查找数据,拿到数据后再经过中间件默认七个关口,经过web服务网关接口后返回给客户端浏览器数据,当第一次请求来时会依次经过url,views最后到数据库拿到数据后由视图层直接到中间件经过七个关口校验,当校验成功后,将数据进入缓存数据库一份,再经过web服务网关接口发送到客户端浏览器一份数据数据库
咱们也能够自定义中间件,须要建立一个文件夹下写自定义中间件代码,而且须要将自定义的中间件配置到配置文件中,自定义中间件要继承中间件继承的 MiddlewraeMixindjango
Django容许自定义中间件而且暴露给用户五个自定义的方法浏览器
一、中间件是在执行视图函数以前执行的缓存
二、请求来的时候会按照配置文件中注册的中间件从上往下的顺序依次执行每个中间件里面的process_request方法,若是没有就直接跳过执行下一个服务器
三、若是中间有一个中间件有return HttpResponse ,就不会再执行后面的了,就直接同级别执行process_response后返回数据cookie
# 自定义的中间件 from django.utils.deprecation import MiddlewareMixin class Mymd1(MiddlewareMixin): def process_request(self, request): print('我是第1个process_request') class Mymd2(MiddlewareMixin): def process_request(self, request): print('我是第2个process_request')
# settings中配置 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'mymiddlewrae.mymiddle.Mymd1', 'mymiddlewrae.mymiddle.Mymd2', ]
# views中 def index(request): print('index') return HttpResponse('index')
最后运行打印结果session
我是第1个process_request
我是第2个process_request
index
响应走的时候会按照配置文件中注册的中间件从下往上依次执行每个中间件里面的process_response方法,该方法必需要有两个形参,且必需要将形参response返回,若是中间件内部定义了HttpResponse对象,返回的时候就会将返回给用户浏览器的内容替换成本身的
# 自定义的中间件 from django.utils.deprecation import MiddlewareMixin class Mymd1(MiddlewareMixin): def process_request(self, request): print('我是第1个process_request') def process_response(self, request, response): print('我是第1个process_response') return response class Mymd2(MiddlewareMixin): def process_request(self, request): print('我是第2个process_request') def process_response(self, request, response): print('我是第2个process_response') return response
最后返回的结果:
我是第1个process_request
我是第2个process_request
index
我是第2个process_response
我是第1个process_response
路由匹配成功以后,进入视图函数以前触发
也必需要有两个参数,response必需要方法,有response的都要返回
视图函数返回的对象中必需要有render属性对应的方法,必需要自定义的render方法
# 视图函数中 def index(request): print('index') def render(): return HttpResponse('我是index中的render方法') obj = HttpResponse('index') obj.render = render return obj
# 自定义中间件 def process_template_response(self,request, response): print('我是第2个process_temlate_response') return response
当视图函数报错时自动触发
# 中间件中 def process_exception(self,request,exception): print('exception:',exception)
钓鱼网站:本质就是搭建一个跟正常网站如出一辙的页面,用户在该页面上完成转帐功能,在给用户书写的form表单中,对方帐户的input中没有name属性,本身偷偷地提早写好一个默认隐藏的具备name属性的input框
<form action="http://127.0.0.1:8000/transfer/" method="post"> <p>username:<input type="text" name="username"></p> <p>target_user:<input type="text"></p> <input type="text" name="target_user" style="display: none" value="jason"> <p>money:<input type="text" name="money"></p> <input type="submit"> </form>
为了防止这种状况发生,咱们能够在咱们的网站设置csrf_token校验,来防止跨站伪造请求
原理:由token产生随机字符串,每次请求都会新生成不一样的,服务器会将须要用户填写数据的(post请求)给她一个随机字符串,下次发送请求的时候会校验是否有那个字符串
在form表单内任意位置书写代码:
{% csrf_token %}
在data中校验csrf
一、第一种方式:手动获取
$.ajax({
url: '',
type: 'post',
{#第一种方法:手动获取#}
data: {'username':'shen', 'csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val()},
success:function (data) {
...
}
})
二、第二种方式:利用模板语法
$.ajax({
url: '',
type: 'post',
{#第二种方法:利用模板语法#}
data: {'username':'shen', 'csrfmiddlewaretoken':{{ csrf_token }},
success:function (data) {
...
}
})
三、第三种方式:通用方式引用外部js文件使全部的post请求都要校验
外部js文件:
function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('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); } } });
引用外部js文件后Ajax就能够正常写提交请求,就能够了
<button id="d1">发送Ajax请求</button> {% load static %} <script src="{% static 'mycsrf.js' %}"></script> <script> $('#d1').click(function () { $.ajax({ url: '', type: 'post', {#第三种方法:引用外部js文件,Ajax不要任何操做#} data: {'username':'shen'}, success:function (data) { alert(data) } }) }) </script>
一、当咱们网站引用外部js文件使得整个网站都须要校验csrf时,想让几个视图函数不校验时,使用csrf_exempt 装饰器使得某个视图函数不校验csrf
二、当咱们网站总体都不校验csrf的时候,想让某几个视图函数校验csrf,能够使用装饰器 csrf_protect
首先咱们须要导入该装饰器
from django.views.decorators.csrf import csrf_exempt, csrf_protect
直接在视图函数上装饰@csrf_protect和@csrf_exempt
# @csrf_exempt # 不校验csrf @csrf_protect # 校验csrf def home(request): if request.method == 'POST': username = request.POST.get('username') print(username) return render(request, 'mycsrf.html')
首先须要导入csrf_exempt,csrf_protect和method_decorator
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views import View from django.utils.decorators import method_decorator
一、csrf_protect 校验csrf
第一种方式:直接在类中的方法使用 @method_decorator(csrf_protect)
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views import View from django.utils.decorators import method_decorator class Myhome(View): # 第一种方式,直接在类中方法使用 @method_decorator(csrf_protect) def get(self,request): return HttpResponse('get')
第二种方式:给类加装饰器,指名道姓的给类中的某个方法
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views import View from django.utils.decorators import method_decorator # 第二种方法,指名道姓给类中post方法装 @method_decorator(csrf_protect, name='post') class Myhome(View): def get(self,request): return HttpResponse('get') def post(self, request): return HttpResponse('post')
第三种方式:给类中的dispatch方法装,使全部的方法都得到csrf校验
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views import View from django.utils.decorators import method_decorator class Myhome(View): # 第三种方式,给类中的全部方法都装 @method_decorator(csrf_protect) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self,request): return HttpResponse('get') def post(self, request): return HttpResponse('post')
二、csrf_exempt 不校验csrf
只能给类中的dispatch方法装,使得全部的方法都得到,或者给类装指明是给dispatch的也能够
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views import View from django.utils.decorators import method_decorator # 给类中全部的方法都装,使得都不校验csrf,与直接给dispatch装同样的 @method_decorator(csrf_exempt, name='dispatch') class Myhome(View): # 给类中的全部方法都装 @method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self,request): return HttpResponse('get') def post(self, request): return HttpResponse('post')