Django 中间件简介

django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。

在django项目的settings模块中,有一个 MIDDLEWARE_CLASSES 变量,其中每一个元素就是一个中间件

中间件中一共有四个方法:

process_request(self,request) 发送请求

process_view(self, request, callback, callback_args, callback_kwargs) 执行完 request 预处理函数并确定待执行的 view 之后,但在 view 函数实际执行之前。

process_exception(self, request, exception) 收集错误信息

process_response(self, request, response) 必须返回 HttpResponse 对象. 这个 response 对象可以是传入函数的那一个原始对象(通常已被修改),也可以是全新生成的。

中间件之  process_request,process_response

process_request(self,request)

process_response(self, request, response)

当用户发起请求的时候会依次经过所有的的中间件,这个时候的请求时process_request,最后到达views的函数中,views函数处理后,在依次穿过中间件,这个时候是process_response,最后返回给请求者

在django中叫中间件,在其他web框架中,有的叫管道,httphandle

中间件都是django中的,我们也可以自己定义一个中间件,我们可以自己写一个类,但是必须继承MiddlewareMixin

需要注意的是顺序,因为是列表或者元组的顺序,注册时按照你既定顺序来配置

所以需要导入:from django.utils.deprecation import MiddlewareMixin

项目文件下创建一个Middle目录,并在下面创建md.py代码例子如下:

#from django.utils.deprecation import MiddlewareMixin
#建议定义类使用MiddlewareMixin class MiddlewareMixin(object):
def __init__(self, get_response=None):
self.get_response = get_response
super(MiddlewareMixin, self).__init__() def __call__(self, request):
response = None
if hasattr(self, 'process_request'):
response = self.process_request(request)
if not response:
response = self.get_response(request)
if hasattr(self, 'process_response'):
response = self.process_response(request, response)
return response class M1(MiddlewareMixin): def process_request(self,request,*args,**kwargs): print('m1.process_request')
print("中间件1请求") def process_response(self, request, response):
print('m1.process_response')
print("中间件1返回")
return response class M2(MiddlewareMixin):
def process_request(self,request,*args,**kwargs):
print('m2.process_request')
print("中间件2请求") def process_response(self, request, response):
print('m2.process_response')
print("中间件2返回")
return response

这样当页面发起请求的时候:后台效果如下

中间件之process_view

process_view(self, request, callback, callback_args, callback_kwargs)

我们在md.py文件中的的代码进行更改:

from django.conf import settings
from django.shortcuts import redirect,HttpResponse class MiddlewareMixin(object):
def __init__(self, get_response=None):
self.get_response = get_response
super(MiddlewareMixin, self).__init__() def __call__(self, request):
response = None
if hasattr(self, 'process_request'):
response = self.process_request(request)
if not response:
response = self.get_response(request)
if hasattr(self, 'process_response'):
response = self.process_response(request, response)
return response class M1(MiddlewareMixin): def process_request(self,request,*args,**kwargs): print('m1.process_request')
print("中间件1请求") def process_response(self, request, response):
print('m1.process_response')
print("中间件1返回")
return response def process_view(self, request, callback, callback_args, callback_kwargs):
print("中间件1view") class M2(MiddlewareMixin):
def process_request(self,request,*args,**kwargs):
print('m2.process_request')
print("中间件2请求") def process_response(self, request, response):
print('m2.process_response')
print("中间件2返回")
return response
def process_view(self, request, callback, callback_args, callback_kwargs):
print("中间件2view")

运行之后效果

Django 中间件简介的更多相关文章

  1. Django中间件(含Django运行周期流程图)

    Django中的中间件(含Django完整生命周期图) Django中间件简介 django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,djang ...

  2. Django—中间件

    中间件简介 什么是中间件 中间件是一个用来处理Django的请求和响应的框架级别的钩子.它是一个轻量.低级别的插件系统,用于在全局范围内改变Django的输入和输出.每个中间件组件都负责做一些特定的功 ...

  3. Django框架简介与使用注意事项

    一.Django框架简介 MVC框架和MTV框架 MVC框架 MVC,全名是Model View Controller,是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model). ...

  4. Django中间件部分源码分析

    中间件源码分析 中间件简介 中间件是一个用来处理Django的请求和响应的框架级别的钩子.它是一个轻量.低级别的插件系统,用于在全局范围内改变Django的输入和输出.每个中间件组件都负责做一些特定的 ...

  5. Django中间件梳理

    Django之中间件   中间件简介 什么是中间件 中间件是一个用来处理Django的请求和响应的框架级别的钩子.它是一个轻量.低级别的插件系统,用于在全局范围内改变Django的输入和输出.每个中间 ...

  6. Django数据操作F和Q、model多对多操作、Django中间件、信号、读数据库里的数据实现分页

    models.tb.objects.all().using('default'),根据using来指定在哪个库里查询,default是settings中配置的数据库的连接名称. 外话:django中引 ...

  7. django 中间件

    django处理一个Request的过程是首先通过django 中间件,然后再通过默认的URL方式进行的.所以说我们要做的就是在django 中间件这个地方把所有Request拦截住,用我们自己的方式 ...

  8. day20 FORM补充(随时更新),F/Q操作,model之多对多,django中间件,缓存,信号

    python-day20 1.FROM生成select标签的数据应该来源于数据库. 2.model 操作 F/Q  (组合查询) 3.model 多对多操作. 4.中间件 :在请求到达url前先会经过 ...

  9. Django Middleware简介

    1      前言 Django使用非常熟练了,各种API接口不在话下,全都搞定.为方便定位问题在每个API接口的的开始和返回的地方都加上了log打印,记录入参和返回值. 但是这样有一个问题,需要每个 ...

随机推荐

  1. 【BZOJ】1661: [Usaco2006 Nov]Big Square 巨大正方形(暴力)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1661 暴力大法好... 枚举对角线(注意,一种对角线2种情况就行了,自己想...) 然后可以算出其它 ...

  2. hdu 5078

    Osu! Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others) Total Sub ...

  3. openldap+php-ldap操作

    一.基础知识首先,如果您对LDAP 不认识,建议先看看[原]LDAP服务介绍一文.本文以Linux 下常用的OpenLDAP为例说明.LDAP 以数方式存放数据,每个节点可存放属性或作为下面节点的父节 ...

  4. hdu 4067(最小费用最大流)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4067 思路:很神奇的建图,参考大牛的: 如果人为添加t->s的边,那么图中所有顶点要满足的条件都 ...

  5. java 环境变量classpath的作用

    http://www.cnblogs.com/xwdreamer/archive/2010/09/08/2297098.html http://www.cnblogs.com/panxuejun/p/ ...

  6. HibernateSessionFactory演示样例

    package common; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hi ...

  7. Spring框架中的AOP技术----注解方式

    利用AOP技术注解的方式对功能进行增强 CustomerDao接口 package com.alphajuns.demo1; public interface CustomerDao { public ...

  8. iOS 将金钱变为逗号形式

    ; NSNumberFormatter * formatter = [NSNumberFormatter new]; [formatter setNumberStyle:NSNumberFormatt ...

  9. [LintCode] 最后一个单词的长度

    class Solution { public: /** * @param s A string * @return the length of last word */ int lengthOfLa ...

  10. ETCD使用中需要注意的问题

    我们在实际生产中使用ETCD存储元数据, 起初集群规模不大的时候元数据信息不多没有发现什么问题. 随着集群规模越来越大问题逐渐暴露了 有些实际的配置还是需要在初始化的时候就研究确定 1. --auto ...