Django基础之中间件
内容概要
-
django中间件
-
csrf跨站请求伪造
django中间件
类似于是django的门户 请求来的时候和响应走的时候都必须经过它
配置文件中 MIDDLEWARE = [ ... ] # django默认有七个中间件 '''每个中间件你可以简单的理解为具有不同的功能''' # django中间件有五个我们需要知道的方法 需要掌握 process_request process_response 需要了解 process_view process_exception process_template_response # django支持用户自定义中间件 django中间件可以用于编写全局相关的功能 eg:全局身份校验 全局防爬校验
中间件使用
from django.utils.deprecation import MiddlewareMixin class MyMiddleware1(MiddlewareMixin): def process_request(self,request): print('from 自定义MyMiddleware1 process_request方法') # 1.请求来的时候会依次(从上往下)执行配置文件中注册了的中间件里面的process_request方法 如果没有直接跳过 # 2.该方法如果直接返回了HttpResponse对象那么请求不再继续往下而是直接原路返回 def process_response(self,request,response): print('from 自定义MyMiddleware1 process_response方法') # 1.响应走的时候从下往上依次执行注册了的中间件里面的process_response方法如果没有则直接跳过 # 2.该方法需要将形参response返回 该response其实就是视图函数返回给浏览器的数据 # 3.该方法还可以拦截返回给浏览器的数据 并且还支持自定义返回内容 """ 当process_request自己返回HttpResponse对象之后 响应是从同级别的process_response依次返回 而不是所有的process_response """
了解方法
process_view 路由匹配成功之后执行视图函数之前自动触发 self,request,view_name,*args,**kwargs process_exception 当视图函数报错之后自动执行 self,request,exception process_template_response self,request,response 图函数返回的对象有一个response()方法(或者表明该对象是一个TemplateResponse对象或等价方法)
csrf跨站请求伪造
钓鱼网站
理论:
做一个与正规网站一模一样的界面 用户在上面操作
比如转账
转账请求确实是发送给了正规的网站后台只不过收款人变成了
钓鱼网站指定的账户
原理:
获取用户输入的表单内
给用户展示了一个没有name属性的框
自己偷偷的写了一个既有name又有value的隐藏框
csrf使用
1.form表单 表单中直接书写下列的语句即可 {% csrf_token %} 2.ajax 方式1:借助于{% csrf_token %}生成的标签(不推荐) $("[name = 'csrfmiddlewaretoken']").val() 方式2:借助于模板语法直接获取 '{{ csrf_token }}' 方式3:借助于官方提供的js文件自动获取 js文件导入即可
csrf相关装饰器
from django.views.decorators.csrf import csrf_exempt, csrf_protect # csrf_exempt 局部不校验csrf # csrf_protect 局部校验csrf # @csrf_protect # @csrf_exempt def index(request): if request.method == 'POST': username = request.POST.get('username') money = request.POST.get('money') target_user = request.POST.get('target_user') print('%s 给 %s 转了 %s 元钱'%(username,target_user,money)) return render(request,'index.html') from django.utils.decorators import method_decorator from django import views # @method_decorator(csrf_protect,name='post') # 第二种 行 # @method_decorator(csrf_exempt,name='post') # 第二种 不行 class MyLogin(views.View): # @method_decorator(csrf_protect) # 第三种 所有的方法都会加上该功能 @method_decorator(csrf_exempt) # 第三种 所有的方法都会加上该功能 def dispatch(self, request, *args, **kwargs): return super().dispatch(request,*args,**kwargs) def get(self,request): return HttpResponse('from get') # @method_decorator(csrf_protect) # 第一种 行 # @method_decorator(csrf_exempt) # 第一种 不行 def post(self,request): return HttpResponse('from post') """ csrf_exempt该装饰器在CBV中只能给dispatch装才能生效 """
愿君前程似锦,归来仍是少年