中间件
- 一个轻量级底层的插件系统,可以介入Django的请求和响应过程,修改Django的输入或输出
- 每一个中间件组件是一个独立的python类。可以定义下面方法中的一个或多个
__init__: 无需任何参数,服务器响应第一个请求的时候调用一次,用于确定是否启用当前中间件
process_request(request): 执行视图之前被调用,在每个请求上调用,返回None或HttpResponse对象
process_view(request, view_func, view_args, view_kwargs): 调用视图之前被调用,在每个请求上调用,返回None或HttpResponse
process_template_response(request.reponse): 在视图刚好执行完毕之后被调用,在每个请求上调用,返回实现了render方法的响应对象
process_response(request, response): 所有响应返回浏览器之前被调用,在每个请求上调用,返回HttpResponse对象
process_exception(request, response, exception): 当视图抛出异常时调用,在每个请求上调用,返回一个HttpResponse对象
- 如果你想干预哪个环节 只需编写对应的类做处理并注册到中间件调用的配置文件中
1 # RBAC中间件案例 2 3 import re 4 from django.shortcuts import redirect, HttpResponse 5 from django.conf import settings 6 7 8 class MiddlewareMixin(object): 9 def __init__(self, get_response=None):10 self.get_response = get_response11 super(MiddlewareMixin, self).__init__()12 13 def __call__(self, request):14 response = None15 if hasattr(self, 'process_request'):16 response = self.process_request(request)17 if not response:18 response = self.get_response(request)19 if hasattr(self, 'process_response'):20 response = self.process_response(request, response)21 return response22 23 24 class LoginMiddleware(MiddlewareMixin):25 26 def process_request(self, request):27 # login页面放行28 if request.path_info == '/stark11/login/':29 return None30 # 已经登录了放行31 if request.session.get('user_info'):32 return None33 # 否则返回login页面34 return redirect('/stark11/login/')35 36 37 class RbacMiddleware(MiddlewareMixin):38 39 def process_request(self, request):40 # 1. 获取当前请求的URL41 # request.path_info42 # 2. 获取Session中保存当前用户的权限43 # request.session.get("permission_url_list')44 current_url = request.path_info45 46 # 当前请求不需要执行权限验证47 for url in settings.VALID_URL:48 if re.match(url, current_url):49 return None50 51 permission_dict = request.session.get(settings.PERMISSION_URL_DICT_KEY)52 if not permission_dict:53 return redirect('/stark11/login/')54 55 flag = False56 for group_id, code_url in permission_dict.items():57 58 for db_url in code_url['urls']:59 regax = "^{0}$".format(db_url)60 if re.match(regax, current_url):61 request.permission_code_list = code_url['codes']62 flag = True63 break64 if flag:65 break66 67 if not flag:68 return HttpResponse('无权访问')