緩存系統 | Django自帶 | Django開發
阿新 • • 發佈:2017-10-29
strong 沒有 版本 reat 實例 sca ken all func
-- 緩存 # 減少重復消耗計算資源; # Django自帶一個健壯的緩存系統來保存動態頁面; 1.設置緩存 -- 設置數據緩存地址:1.數據庫;2.文件系統; -- settings.py中的CACHES配置: # 參數TIMEOUT:緩存過期時間; # 默認300秒; # 下面是對存到本地的配置: # None表示永久,0表示立即失效; # CACHES={ # ‘default‘: { #‘BACKEND‘: ‘django.core.cache.backends.locmem.LocMemCache‘, # ‘TIMEOUT‘: 60, # } # } -- 將緩存保存到redis中 # 默認使用其中的數據庫1; # 安裝包:pip install django-redis-cache # CACHES = { # "default": { #"BACKEND": "redis_cache.cache.RedisCache", # "LOCATION": "localhost:6379", # ‘TIMEOUT‘: 60, # }, # } -- 連接redis查看存的數據 # 連接:redis-cli # 切換數據庫:select 1 # 查看鍵:keys * # 查看值:get 鍵2.單個view緩存 2.1 緩存一個視圖函數 -- 導入一個模塊 from django.views.decorators.cache import cache_page -- 在視圖函數上加上一個裝飾器 @cache_page(60 * 15) # 裝飾器中傳入的timeout參數指的是時間; def index(request): return HttpResponse(‘hello1‘) # 附:視圖緩存與URL無關,如果多個URL指向同一視圖,每個URL將會分別緩存 3.模板片段緩存 -- 使用cache模板標簽來緩存模板的一個片段 -- 需要兩個參數: # 緩存時間,以秒為單位 # 給緩存片段起的名稱 # {% load cache %} # {% cache 500 hello %} # hello1 # <!--hello2--> # {% endcache %} 4.底層的緩存API from django.core.cache import cache # 設置:cache.set(鍵,值,有效時間) # 獲取:cache.get(鍵) # 刪除:cache.delete(鍵) # 清空:cache.clear()
------------------------------------------------------------------>>>>>>>>>> 其他緩存引擎配置
1.DummyCache
# 此為開始調試用,實際內部不做任何操作 # 配置: CACHES = { ‘default‘: { ‘BACKEND‘: ‘django.core.cache.backends.dummy.DummyCache‘, # 引擎 ‘TIMEOUT‘: 300, # 緩存超時時間(默認300,None表示永不過期,0表示立即過期) ‘OPTIONS‘:{ ‘MAX_ENTRIES‘: 300, # 最大緩存個數(默認300) ‘CULL_FREQUENCY‘: 3, # 緩存到達最大個數之後,剔除緩存個數的比例,即:1/CULL_FREQUENCY(默認3) }, ‘KEY_PREFIX‘: ‘‘, # 緩存key的前綴(默認空) ‘VERSION‘: 1, # 緩存key的版本(默認1) ‘KEY_FUNCTION‘ 函數名 # 生成key的函數(默認函數會生成為:【前綴:版本:key】) } } # 自定義key def default_key_func(key, key_prefix, version): """ Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix‘. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ return ‘%s:%s:%s‘ % (key_prefix, version, key) def get_key_func(key_func): """ Function to decide which key function to use. Defaults to ``default_key_func``. """ if key_func is not None: if callable(key_func): return key_func else: return import_string(key_func) return default_key_func
2.DatabaseCache
# 利用數據庫來緩存,利用命令創建相應的表:python manage.py createcachetable cache_table_name CACHES = { ‘default‘: { ‘BACKEND‘: ‘django.core.cache.backends.db.DatabaseCache‘, ‘LOCATION‘: ‘cache_table_name‘, ‘TIMEOUT‘: 600, ‘OPTIONS‘: { ‘MAX_ENTRIES‘: 2000 } } }
3.FileBasedCache
# 利用文件系統來緩存: CACHES = { ‘default‘: { ‘BACKEND‘: ‘django.core.cache.backends.filebased.FileBasedCache‘, ‘LOCATION‘: ‘/var/tmp/django_cache‘, ‘TIMEOUT‘: 600, ‘OPTIONS‘: { ‘MAX_ENTRIES‘: 1000 } } }
4.MemcachedCache
# 此緩存使用python-memcached模塊連接memcache CACHES = { ‘default‘: { ‘BACKEND‘: ‘django.core.cache.backends.memcached.MemcachedCache‘, ‘LOCATION‘: ‘127.0.0.1:11211‘, } } CACHES = { ‘default‘: { ‘BACKEND‘: ‘django.core.cache.backends.memcached.MemcachedCache‘, ‘LOCATION‘: ‘unix:/tmp/memcached.sock‘, } } CACHES = { ‘default‘: { ‘BACKEND‘: ‘django.core.cache.backends.memcached.MemcachedCache‘, ‘LOCATION‘: [ ‘172.19.26.240:11211‘, ‘172.19.26.242:11211‘, ] } }
5.PyLibMCCache
# 此緩存使用pylibmc模塊連接memcache CACHES = { ‘default‘: { ‘BACKEND‘: ‘django.core.cache.backends.memcached.PyLibMCCache‘, ‘LOCATION‘: ‘127.0.0.1:11211‘, } } CACHES = { ‘default‘: { ‘BACKEND‘: ‘django.core.cache.backends.memcached.PyLibMCCache‘, ‘LOCATION‘: ‘/tmp/memcached.sock‘, } } CACHES = { ‘default‘: { ‘BACKEND‘: ‘django.core.cache.backends.memcached.PyLibMCCache‘, ‘LOCATION‘: [ ‘172.19.26.240:11211‘, ‘172.19.26.242:11211‘, ] } }
==========================================》》》》》》使用
1.全站使用
使用中間件,經過一系列的認證等操作,如果內容在緩存中存在,則使用FetchFromCacheMiddleware獲取內容並返回給用戶,當返回給用戶之前,判斷緩存中是否已經存在,如果不存在則UpdateCacheMiddleware會將緩存保存至緩存,從而實現全站緩存 MIDDLEWARE = [ ‘django.middleware.cache.UpdateCacheMiddleware‘, # 其他中間件... ‘django.middleware.cache.FetchFromCacheMiddleware‘, ] CACHE_MIDDLEWARE_ALIAS = "" CACHE_MIDDLEWARE_SECONDS = "" CACHE_MIDDLEWARE_KEY_PREFIX = ""
2.單獨視圖緩存
方式一: from django.views.decorators.cache import cache_page @cache_page(60 * 15) def my_view(request): ... 方式二: from django.views.decorators.cache import cache_page urlpatterns = [ url(r‘^foo/([0-9]{1,2})/$‘, cache_page(60 * 15)(my_view)), ]
3.模板局部視圖使用
1. 引入TemplateTag {% load cache %} 2. 使用緩存 {% cache 5000 緩存key %} 緩存內容 {% endcache %}
4.實例演示
# 一般來說我們用 Django 來搭建一個網站,要用到數據庫等。 from django.shortcuts import render def index(request): # 讀取數據庫等 並渲染到網頁 # 數據庫獲取的結果保存到 queryset 中 return render(request, ‘index.html‘, {‘queryset‘:queryset}) # 像這樣每次訪問都要讀取數據庫,一般的小網站沒什麽問題,當訪問量非常大的時候,就會有很多次的數據庫查詢,肯定會造成訪問速度變慢,服務器資源占用較多等問題。 #------------------------------------------ #------------------------------------------ from django.shortcuts import render from django.views.decorators.cache import cache_page @cache_page(60 * 15) # 秒數,這裏指緩存 15 分鐘,不直接寫900是為了提高可讀性 def index(request): # 讀取數據庫等 並渲染到網頁 return render(request, ‘index.html‘, {‘queryset‘:queryset}) # 當使用了cache後,訪問情況變成了如下: # 訪問一個網址時, 嘗試從 cache 中找有沒有緩存內容 # 如果網頁在緩存中顯示緩存內容,否則生成訪問的頁面,保存在緩存中以便下次使用,顯示緩存的頁面。 # given a URL, try finding that page in the cache # if the page is in the cache: # return the cached page # else: # generate the page # save the generated page in the cache (for next time) # return the generated page # Memcached 是目前 Django 可用的最快的緩存
緩存系統 | Django自帶 | Django開發