django 中的中間件(middleware),在django中,中間件其實就是一個類,在請求到來和結束後,django會根據本身的規則在合適的時機執行中間件中相應的方法。python
在django項目的settings模塊中,有一個 MIDDLEWARE 變量,其中每個元素就是一箇中間件,以下圖。redis
中間件中能夠定義四個方法,分別是:數據庫
以上方法的返回值能夠是None和HttpResonse對象,若是是None,則繼續按照django定義的規則向下執行,若是是HttpResonse對象,則直接將該對象返回給用戶。django
1.建立中間件類(新建文件夾Middle--->m1.py)緩存
1 from django.utils.deprecation import MiddlewareMixin 2 from django.shortcuts import HttpResponse 3 class Row1(MiddlewareMixin): 4 def process_request(self,request): 5 print("111") 6 7 def process_view(self, request, view_func, view_func_args, view_func_kwargs): 8 print("444") 9 10 def process_response(self,request,response): 11 print("999") 12 return response 13 14 class Row2(MiddlewareMixin): 15 def process_request(self,request): 16 print("222") 17 # return HttpResponse("gun") 18 19 def process_view(self, request, view_func, view_func_args, view_func_kwargs): 20 print("555") 21 22 def process_response(self,request,response): 23 print("888") 24 return response 25 26 27 class Row3(MiddlewareMixin): 28 def process_request(self,request): 29 print("333") 30 31 def process_view(self, request, view_func, view_func_args, view_func_kwargs): 32 print("666") 33 34 def process_response(self,request,response): 35 print("777") 36 return response
2.註冊中間件settingssession
1 MIDDLEWARE = [ 2 'django.middleware.security.SecurityMiddleware', 3 'django.contrib.sessions.middleware.SessionMiddleware', 4 'django.middleware.common.CommonMiddleware', 5 'django.middleware.csrf.CsrfViewMiddleware', 6 'django.contrib.auth.middleware.AuthenticationMiddleware', 7 'django.contrib.messages.middleware.MessageMiddleware', 8 'django.middleware.clickjacking.XFrameOptionsMiddleware', 9 "Middle.m1.Row1", 10 "Middle.m1.Row2", 11 "Middle.m1.Row3", 12 ]
3.異常數據處理(主要是views中出現異常)app
1 from django.utils.deprecation import MiddlewareMixin 2 from django.shortcuts import HttpResponse 3 class Row1(MiddlewareMixin): 4 def process_request(self,request): 5 print("111") 6 7 def process_view(self, request, view_func, view_func_args, view_func_kwargs): 8 print("444") 9 10 def process_response(self,request,response): 11 print("999") 12 return response 13 14 class Row2(MiddlewareMixin): 15 def process_request(self,request): 16 print("222") 17 # return HttpResponse("gun") 18 19 def process_view(self, request, view_func, view_func_args, view_func_kwargs): 20 print("555") 21 22 def process_response(self,request,response): 23 print("888") 24 return response 25 26 27 class Row3(MiddlewareMixin): 28 def process_request(self,request): 29 print("333") 30 31 def process_view(self, request, view_func, view_func_args, view_func_kwargs): 32 print("666") 33 34 def process_response(self,request,response): 35 print("777") 36 return response 37 38 def process_exception(self, request, exception): 39 if isinstance(exception,ValueError): 40 print("error") 41 return HttpResponse("出現異常。。。。。")
實際效果: 框架
因爲Django是動態網站,全部每次請求均會去數據進行相應的操做,當程序訪問量大時,耗時必然會更加明顯,最簡單解決方式是使用:緩存,緩存將一個某個views的返回值保存至內存或者memcache中,5分鐘內再有人來訪問時,則再也不去執行view中的操做,而是直接從內存或者Redis中以前緩存的內容拿到,並返回。ide
Django中提供了6種緩存方式:memcached
開發調試
1 # 此爲開始調試用,實際內部不作任何操做 2 # 配置: 3 CACHES = { 4 'default': { 5 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', # 引擎 6 'TIMEOUT': 300, # 緩存超時時間(默認300,None表示永不過時,0表示當即過時) 7 'OPTIONS':{ 8 'MAX_ENTRIES': 300, # 最大緩存個數(默認300) 9 'CULL_FREQUENCY': 3, # 緩存到達最大個數以後,剔除緩存個數的比例,即:1/CULL_FREQUENCY(默認3) 10 }, 11 'KEY_PREFIX': '', # 緩存key的前綴(默認空) 12 'VERSION': 1, # 緩存key的版本(默認1) 13 'KEY_FUNCTION' 函數名 # 生成key的函數(默認函數會生成爲:【前綴:版本:key】) 14 } 15 } 16 17 18 # 自定義key 19 def default_key_func(key, key_prefix, version): 20 """ 21 Default function to generate keys. 22 23 Constructs the key used by all other methods. By default it prepends 24 the `key_prefix'. KEY_FUNCTION can be used to specify an alternate 25 function with custom key making behavior. 26 """ 27 return '%s:%s:%s' % (key_prefix, version, key) 28 29 def get_key_func(key_func): 30 """ 31 Function to decide which key function to use. 32 33 Defaults to ``default_key_func``. 34 """ 35 if key_func is not None: 36 if callable(key_func): 37 return key_func 38 else: 39 return import_string(key_func) 40 return default_key_func
內存
1 # 此緩存將內容保存至內存的變量中 2 # 配置: 3 CACHES = { 4 'default': { 5 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 6 'LOCATION': 'unique-snowflake', 7 } 8 } 9 10 # 注:其餘配置同開發調試版本
文件
1 # 此緩存將內容保存至文件 2 # 配置: 3 4 CACHES = { 5 'default': { 6 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 7 'LOCATION': '/var/tmp/django_cache', 8 } 9 } 10 # 注:其餘配置同開發調試版本
數據庫
1 # 此緩存將內容保存至數據庫 2 3 # 配置: 4 CACHES = { 5 'default': { 6 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 7 'LOCATION': 'my_cache_table', # 數據庫表 8 } 9 } 10 11 # 注:執行建立表命令 python manage.py createcachetable
Memcache緩存(python-memcached模塊)
1 # 此緩存使用python-memcached模塊鏈接memcache 2 3 CACHES = { 4 'default': { 5 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 6 'LOCATION': '127.0.0.1:11211', 7 } 8 } 9 10 CACHES = { 11 'default': { 12 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 13 'LOCATION': 'unix:/tmp/memcached.sock', 14 } 15 } 16 17 CACHES = { 18 'default': { 19 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 20 'LOCATION': [ 21 '172.19.26.240:11211', 22 '172.19.26.242:11211', 23 ] 24 } 25 }
Memcache緩存(pylibmc模塊)
1 # 此緩存使用pylibmc模塊鏈接memcache 2 3 CACHES = { 4 'default': { 5 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 6 'LOCATION': '127.0.0.1:11211', 7 } 8 } 9 10 CACHES = { 11 'default': { 12 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 13 'LOCATION': '/tmp/memcached.sock', 14 } 15 } 16 17 CACHES = { 18 'default': { 19 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 20 'LOCATION': [ 21 '172.19.26.240:11211', 22 '172.19.26.242:11211', 23 ] 24 } 25 }
Redis緩存(依賴:pip3 install django-redis)
1 CACHES = { 2 "default": { 3 "BACKEND": "django_redis.cache.RedisCache", 4 "LOCATION": "redis://127.0.0.1:6379", 5 "OPTIONS": { 6 "CLIENT_CLASS": "django_redis.client.DefaultClient", 7 "CONNECTION_POOL_KWARGS": {"max_connections": 100} 8 # "PASSWORD": "密碼", 9 } 10 } 11 }
1 from django_redis import get_redis_connection 2 conn = get_redis_connection("default")
全站應用
1 使用中間件,通過一系列的認證等操做,若是內容在緩存中存在,則使用FetchFromCacheMiddleware獲取內容並返回給用戶,當返回給用戶以前,判斷緩存中是否已經存在,若是不存在則UpdateCacheMiddleware會將緩存保存至緩存,從而實現全站緩存 2 3 MIDDLEWARE = [ 4 'django.middleware.cache.UpdateCacheMiddleware', 5 # 其餘中間件... 6 'django.middleware.cache.FetchFromCacheMiddleware', 7 ] 8 9 CACHE_MIDDLEWARE_ALIAS = "" 10 CACHE_MIDDLEWARE_SECONDS = "" 11 CACHE_MIDDLEWARE_KEY_PREFIX = ""
單獨視圖緩存應用
1 方式一: 2 from django.views.decorators.cache import cache_page 3 4 @cache_page(60 * 15) 5 def my_view(request): 6 ... 7 8 方式二: 9 from django.views.decorators.cache import cache_page 10 11 urlpatterns = [ 12 url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)), 13 ]
視圖模板緩存應用
a. 引入TemplateTag {% load cache %} b. 使用緩存 {% cache 5000 緩存key %} 緩存內容 {% endcache %} 5000:超時時間
Django中提供了「信號調度」,用於在框架執行操做時解耦。通俗來說,就是一些動做發生的時候,信號容許特定的發送者去提醒一些接受者。
1 Model signals 2 pre_init # django的modal執行其構造方法前,自動觸發 3 post_init # django的modal執行其構造方法後,自動觸發 4 pre_save # django的modal對象保存前,自動觸發 5 post_save # django的modal對象保存後,自動觸發 6 pre_delete # django的modal對象刪除前,自動觸發 7 post_delete # django的modal對象刪除後,自動觸發 8 m2m_changed # django的modal中使用m2m字段操做第三張表(add,remove,clear)先後,自動觸發 9 class_prepared # 程序啓動時,檢測已註冊的app中modal類,對於每個類,自動觸發 10 Management signals 11 pre_migrate # 執行migrate命令前,自動觸發 12 post_migrate # 執行migrate命令後,自動觸發 13 Request/response signals 14 request_started # 請求到來前,自動觸發 15 request_finished # 請求結束後,自動觸發 16 got_request_exception # 請求異常後,自動觸發 17 Test signals 18 setting_changed # 使用test測試修改配置文件時,自動觸發 19 template_rendered # 使用test測試渲染模板時,自動觸發 20 Database Wrappers 21 connection_created # 建立數據庫鏈接時,自動觸發
對於Django內置的信號,僅需註冊指定信號,當程序執行相應操做時,自動觸發註冊函數:
1 from django.core.signals import request_finished 2 from django.core.signals import request_started 3 from django.core.signals import got_request_exception 4 5 from django.db.models.signals import class_prepared 6 from django.db.models.signals import pre_init, post_init 7 from django.db.models.signals import pre_save, post_save 8 from django.db.models.signals import pre_delete, post_delete 9 from django.db.models.signals import m2m_changed 10 from django.db.models.signals import pre_migrate, post_migrate 11 12 from django.test.signals import setting_changed 13 from django.test.signals import template_rendered 14 15 from django.db.backends.signals import connection_created 16 17 18 def callback(sender, **kwargs): 19 print("xxoo_callback") 20 print(sender,kwargs) 21 22 xxoo.connect(callback) 23 # xxoo指上述導入的內容
1 from django.core.signals import request_finished 2 from django.dispatch import receiver 3 4 @receiver(request_finished) 5 def my_callback(sender, **kwargs): 6 print("Request finished!")
1.定義信號
1 import django.dispatch 2 pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
2.註冊信號
1 def callback(sender, **kwargs): 2 print("callback") 3 print(sender,kwargs) 4 5 pizza_done.connect(callback)
3. 觸發信號
from 路徑 import pizza_done pizza_done.send(sender='seven',toppings=123, size=456)
因爲內置信號的觸發者已經集成到Django中,因此其會自動調用,而對於自定義信號則須要開發者在任意位置觸發。