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',
)

請注意,這裡的順序很重要,Update 應該在 Fetch 中介軟體之前。

然後在同一個檔案中,您需要設定:

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 %}

如上所示,cache 標籤將有兩個引數:您希望快取塊的時間(以秒為單位)和賦予快取片段的名稱。

廣告