缓存某些内容是为了保存昂贵计算的结果,因此您不会在下次需要时执行此操作.以下是一个伪代码,解释缓存的工作方式和减号;
given a URL, try finding that page in the cacheif the page is in the cache: return the cached pageelse: generate the page save the generated page in the cache (for next time) return the generated page
Django带有自己的缓存系统,可以保存动态页面,以避免在需要时再次计算它们. Django Cache框架的优点是你可以缓存 :
特定视图的输出.
模板的一部分.
您的整个网站.
在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',)
<请注意,顺序在这里很重要,更新应该在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 装饰器完成的.我们假设我们想要从django.views.decorators缓存 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\d{2})/(?P \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\d{2})/(?P \d{4})/', cache_page(60 * 15)('viewArticles'), name = 'articles'),)
当然,myapp/views中不再需要它. py.
缓存模板片段
您还可以缓存部分模板,这可以通过缓存标签.我们来看看 hello.html 模板 :
{% extends "main_template.html" %}{% block title %}My Hello Page{% endblock %}{% block content %}Hello World!!!Today is {{today}}
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%}{% for day in days_of_week %} {{day}}
{% endfor %}{% endblock %}
要缓存内容块,我们的模板将会成为 : 去;
{% load cache %}{% extends "main_template.html" %}{% block title %}My Hello Page{% endblock %}{% cache 500 content %}{% block content %}Hello World!!!Today is {{today}}
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%}{% for day in days_of_week %} {{day}}
{% endfor %}{% endblock %}{% endcache %}
As你可以看到,缓存标签将采用2个参数 : 您希望缓存块的时间(以秒为单位)以及要为缓存片段指定的名称.