中间件定义:

  中间件是一个、一个的管道,如果相对任何所有的通过Django的请求进行管理都需要自定义中间件

  中间件可以对进来的请求和出去的请求进行控制

  中间件是一类。

看下面的代码在settings里中间件的类:

 
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
 

当有请求过来的时候,默认从上倒下执行!然后在返回的时候从下面在返回回去,如下图:

2、自定义中间件

中间件中可以定义四个方法,分别是:

  • process_request(self,request)
  • process_view(self, request, callback, callback_args, callback_kwargs)
  • process_exception(self, request, exception)
  • process_response(self, request, response)

process_exception 这个方法只有在出现错误的时候才会触发

先写一个自定义中间件,然后在看他的原理和源码:

2.1、自定义中间件

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeEAAADiCAIAAAD2y+hDAAAcFUlEQVR4nO3d/W8U173H8fwXVX6kTZNtK1XqraomzrK2eTDCdhzwA04wxohAwOyuCWmaXmzX65RA8AKG1GNwCCQKYscYvDg22JTZoqpqriLdqr2oVUWe/EN1Vd2Hn/v7vT/Mw5552p1de3eOd9+r1w9mPHPm7MH++PjMeL5P9fT0RBubAQDhikQiu/e84vAUGQ0AMiCjAUBelc3oR5cPOozGO0N/zwCwUUQikWddrwpmdEVjuiGWmNI0TVMGY01VG8ECJx1UNE1Tx3p8t4fSYXk07B+dSQ+1V+y9N8QGRmbSiY6Qx7ahY2iiWt3wO5ffUFvbq9lJlCQSifzoxz9xqGxGe1qX05HRZWtPpmdGBxpiuxLpmQ/M18zMaJ/ZsUrknW9wrNO51tjOunWDjPbSNzozkdxVtdNtXMUzOpPJZL1eN2/eLNp6lTNaNkUzOvQe6ho6hib0b9TYrkR6ZmS/d8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PMgXqTTkZPTc3F08mg7S+vmsdRsh6ld/2LPnqqiIYuLBsmfNod0lZ718I7OeyHysUTvR6R7YRAFDzSsvo+fn5d06dijUFbb3wNcP1zWh3PZQgGe1fgnb9M9rnXL4Z7VfhxZx6k9RA7Sshoy9fvtL6UkdJra/vPFpf6+hKqT5rHa6Sr0Ey2rewbOlrHa6Sss4OeJ/LJ6N9itiOxZ0/nwDUsEAZffPmzb7+gTJaX8s1Q+H+aHWsp8kqzCoGor5uUOxyXMGM9i1B653R+V4J1/f8Ssp6zq9d5/LOaPNj2zuKmqVbxGV6ADWssn9nWN48GgCgI6MBQF489w4A5EVGA4C8yGgAkBcZDQDyIqMBQF5kNADIi4wGAHmR0QAgLzIaAORFRgOAvMhoAJAXGQ0A8iKjAUBeZDQAyIuMBgB5kdEAIC8yGgDkRUYDgLzIaACQFxkNAPIiowFAXp4Z/f84w0wkuCs6/gAAAABJRU5ErkJggg==" alt="" />\

 
class Testmiddle(object):
def process_request(self,request):
print 'Testmiddle process_request'
def process_view(self, request, callback, callback_args, callback_kwargs):
print 'Testmiddle process_view'
def process_exception(self, request, exception):
pass
def process_response(self, request, response):
print 'Testmiddle process_response'
return response class Nextmiddle(object):
def process_request(self,request):
print 'Nextmiddle process_request'
def process_view(self, request, callback, callback_args, callback_kwargs):
print 'Nextmiddle process_view'
def process_exception(self, request, exception):
pass
def process_response(self, request, response):
print 'Nextmiddle process_response'
return response
 

2.2、注册中间件

 
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'middleware.middle.Testmiddle',
'middleware.middle.Nextmiddle',
]
 

2.3、测试使用url和views

from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/$', views.index), ]
def index(request):
print 'This app01 Views.index'
return HttpResponse('OK')

2.4、查看输出结果:

 
'''
Testmiddle process_request
Nextmiddle process_request
Testmiddle process_view
Nextmiddle process_view
This app01 Views.index
Nextmiddle process_response
Testmiddle process_response
'''
 

从输出结果可以看出:

他是先执行Testmiddle 的request 方法又执行了Nextmiddle的 process_request方法。。。。

2.5、原理:

当请求进来了到达中间件

去settings里面找到MIDDLEWARE_CLASSES,MIDDLEWARE_CLASSES是一个元组

有4个列表:

 
process_request_lsit = []
process_view_list = []
process_response_list = []
然后他循环MIDDLEWARE_CLASSES这个类:
for 类 in MIDDLEWARE_CLASSES:
  obj = 类()
  if obj里有process_request方法:
    process_request_lsit.append(obj.process_request)
 

然后循环后后执行:

for i in process_request_list:
  i() #加括号执行方法 for i in process_view_list:
i()
............

3、中间件的流程梳理

首先看下自定义的中间件中的process_response方法他是有返回值的其他的是没有返回值的。这个return response是什么呢?

这个response就是咱们自定义的views.index返回的结果!

    def process_response(self, request, response):
print 'Testmiddle process_response'
return response

如果在其他的没有返回值得,仅有process_response有返回值得话他的请求流程是这样的:

但是如果在process_request或者process_view又返回值得话那么流程就完全不一样了!

举例:如果有m1和m2两个中间件,如果我在m1中的request方法中设置了,如果访问为1.1.1.1那么返回要一个404,那么他的访问流程是这样的:

process_exception  什么时候触发呢?咱们定义的views.index出错的时候他就会捕捉到然后执行咱们定义的process_exception方法如下图:

Django缓存

由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用:缓存,缓存将一个某个views的返回值保存至内存或者Redis中,5分钟内再有人来访问时,则不再去执行view中的操作,而是直接从内存或者Redis中之前缓存的内容拿到,并返回。

举个例子来说:如果访问量比较大的时候,有很多相同的操作比如:有时候请求的数据比如访问同一条数据,或者同一个页面的时候,其实是没必要的。

Django支持,mysql,Redis、Memecache、文件的方式做缓存,并且可以设置超时时间。

settings配置:

CACHES = {
'default': {
#定义已文件的方式进行cache
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
#cache文件的存放路径
'LOCATION': os.path.join(BASE_DIR, 'cache'),
#超时时间为600妙
'TIMEOUT': 600,
'OPTIONS': {
'MAX_ENTRIES': 1000
}
}
}

给请求应用,就是使用装饰器

from django.views.decorators.cache import cache_page

#这里设置的是 60秒 * 15 ,15分钟之后
@cache_page(60 * 15)
def cache_page(request):
current = str(time.time())
return HttpResponse(current)

中间件和Django缓存的更多相关文章

  1. django 缓存、中间件、信号、CSRF 详解

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

  2. Django缓存机制

    缓存介绍 在动态网站中,用户所有的请求,服务器都会去数据库中进行相应的增删改查,渲染模板,执行业务逻辑,最后生成用户看到的页面. 当一个网站的用户访问量很大的时候,每一次的后台操作,都会消耗很多的服务 ...

  3. django缓存、信号、序列化

    本篇导航: Django的缓存机制 Django的信号 Django的序列化 一.Django的缓存机制 1.缓存介绍 1)缓存的简介 在动态网站中,用户所有的请求,服务器都会去数据库中进行相应的增, ...

  4. 版本控制,django缓存,跨域问题解决

    复习 分页: 1. 简单分页 2. 偏移分页 3. 加密分页 解析器:客户处理前端提交来的数据 urlencode: body体中的数据格式: key=value& formdata编码:为区 ...

  5. Django 缓存

    官方文档 缓存的出现就是为了减轻对数据库的压力和加快内存访问的速度.我们的访问请求最终都是返回一个大的字符串,缓存就是将这段字符串直接存储起来,下次你来了,不用经过view去数据库或者内存拿到数据再渲 ...

  6. 一.rest-framework之版本控制 二、Django缓存 三、跨域问题 四、drf分页器 五、响应器 六、url控制器

    一.rest-framework之版本控制 1.作用 用于版本的控制 2.内置的版本控制 from rest_framework.versioning import QueryParameterVer ...

  7. Django缓存设置

    由于Django构建得是动态网站,每次客户端请求都要严重依赖数据库,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用:缓存,缓存将一个某个views的返回值保存至内存或者memcache中, ...

  8. Django缓存系统

    在动态网站中,用户每次请求一个页面,服务器都会执行以下操作:查询数据库,渲染模板,执行业务逻辑,最后生成用户可查看的页面. 这会消耗大量的资源,当访问用户量非常大时,就要考虑这个问题了. 缓存就是为了 ...

  9. Django - 缓存应用

    Django缓存应用: https://www.cnblogs.com/zuoshoushizi/p/7850281.html https://www.cnblogs.com/alice-bj/p/9 ...

随机推荐

  1. 举例跟踪linux内核系统调用

    学号351+ 原创作品转载请注明出处 + 中科大孟宁老师的linux操作系统分析: https://github.com/mengning/linuxkernel/ 实验要求: 编译内核5.0 qem ...

  2. linux中常见的命令

    linux 中的命令非常多,但是玩过linux的人也从来不会因为Linux的命令如此之多而烦恼,我们只需要掌握其中常见的命令即可,可以在使用时去找man,会帮助你解决不少问题.下面就列出一些常见的li ...

  3. ansible资产配置

    参考链接:https://www.cnblogs.com/iois/p/6403761.html ansible主机组的使用,我们在对一个集群进行管理的时候集群会有很多角色,在执行统一命令操作的时候我 ...

  4. ubuntu安装后问题

    ubuntu安装后桌面显示不正常,出现闪屏,或者是缺图标的问题多数是ubuntu的3D加速显示问题 解决方法,vmware workstations 中的菜单栏:虚拟机->设置->显示器- ...

  5. RBAC角色权限设计

    https://www.cnblogs.com/vinozly/p/4851364.html

  6. UDP聊天工具的实现

    利用TIdUDPClient;   TIdUDPServer;  实现聊天,其实很不爽,没有解决中文乱码问题,以后补充吧!      代码如下: unit Unit1; interface uses ...

  7. Python Opencv安装环境搭建

    https://blog.csdn.net/weifenglin1997/article/details/78723544

  8. shell练习题1

    需求如下: 写一个shell脚本,把10.0.1.0/24网段在线的ip列出来. 参考解答如下 方法1 #!/bin/bash ip="10.0.1." for i in $(se ...

  9. Leet Code 3. Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. Examples: Giv ...

  10. linux部署小结

    一.连接外网1.配置网卡 vi /etc/sysconfig/network-scripts/ifcfg-eth0 BOOTPROTO=static IPADDR= PREFIX= GATEWAY= ...