Django緩存

若要緩存一些昂貴的計算結果, 下一次你需要它時不需要再執行它。以下是解釋緩存如何工作的偽代碼−
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 

Django提供了自己的緩存系統,可以讓您保存動態網頁,為了避免在需要時重新計算它們。Django緩存架構的優點是,讓你緩存 -

  • 特定視圖的輸出
  • 範本的一部分
  • 整個網站

要使用在Django中使用高速緩存,首先要做的是設置在那裏的緩存會保存下來。高速緩存框架提供了不同的可能性 - 高速緩存可以被保存在資料庫中,關於檔系統,或直接在內存中。可在專案的 settings.py 檔設置完成。

在資料庫設置緩存

只需在專案settings.py檔添加如下-
CACHES = {
   'default': {
      'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
      'LOCATION': 'my_table_name',
   }
} 

對於這項工作,並完成設置,我們需要創建高速緩存表“my_table_name”。對於這一點,需要做到以下幾點 -

python manage.py createcachetable

在檔系統設置高速緩存

只需在專案settings.py檔添加如下-
CACHES = {
   'default': {
      'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
      'LOCATION': '/var/tmp/django_cache',
   }
}

設置緩存在內存中

這是緩存的最有效的方法,你可以使用它這取決於Python綁定庫選擇了記憶體高速緩存,如下列選項之一 -
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',
   }
}

緩存整個網站

使用高速緩存在Django的最簡單的方法就是緩存整個網站。這可以通過編輯專案settings.py的MIDDLEWARE_CLASSES選項來完成。以下需要添加到選項-

MIDDLEWARE_CLASSES += (
   'django.middleware.cache.UpdateCacheMiddleware',
   'django.middleware.common.CommonMiddleware',
   'django.middleware.cache.FetchFromCacheMiddleware',
)
請注意,這裏的順序是很重要的,更新應在獲取中間件之前。
然後在同一個檔,還需要設置 -
CACHE_MIDDLEWARE_ALIAS – The cache alias to use for storage.
CACHE_MIDDLEWARE_SECONDS – The number of seconds each page should be cached.

緩存視圖

如果不想緩存整個網站,可以緩存特定視圖。這可通過使用附帶 Django 的 cache_page 修飾符完成。我們要緩存視圖viewArticles的結果-

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)

def viewArticles(request, year, month):
   text = "Displaying articles of : %s/%s"%(year, month)
   return HttpResponse(text) 

正如你所看到 cache_page 是您希望視圖結果被緩存的需要的秒數(參數)。在上面的例子中,結果將會緩存 15 分鐘。

注 - 正如我們之前看到的上述視圖是映射到 -
urlpatterns = patterns('myapp.views',
   url(r'^articles/(?P<month>\d{2})/(?P<year>\d{4})/', 'viewArticles', name = 'articles'),) 

由於URL使用參數,每一個不同的調用將被單獨地執行緩存。例如,請求 /myapp/articles/02/2007 將分別緩存到 /myapp/articles/03/2008。

緩存一個視圖也可以直接在url.py檔中完成。接著下麵有相同的結果與上所述。只要編輯 myapp/url.py 檔並更改(以上)的相關映射URL為 -

urlpatterns = patterns('myapp.views',
   url(r'^articles/(?P<month>\d{2})/(?P<year>\d{4})/',
   cache_page(60 * 15)('viewArticles'), name = 'articles'),)
當然,它不再需要myapp/views.py。

緩存範本片段

也可以緩存範本的一部分,這是通過使用 cache 標籤進行的。讓我們把 hello.html 範本修改 -
{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}

the first day of month.
{% elif today == 30 %}

the last day of month.
{% else %}

I don't know.
{%endif%}

<p>
   {% for day in days_of_week %}
   {{day}}
</p>

{% endfor %}
{% endblock %}
緩存內容塊範本將成為 -
{% load cache %}
{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% cache 500 content %}
{% block content %}

Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}

the first day of month.
{% elif today == 30 %}

the last day of month.
{% else %}

I don't know.
{%endif%}

<p>
   {% for day in days_of_week %}
   {{day}}
</p>

{% endfor %}
{% endblock %}
{% endcache %} 

正如你可以在上面看到,緩存標籤將需要2個參數 − 想要的塊被緩存(秒)以及名稱提供給緩存片段。


上一篇: Django Session會話 下一篇: Django RSS