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 文件设置完成。
caches = { 'default': { 'backend': 'django.core.cache.backends.db.databasecache', 'location': 'my_table_name', } }
对于这项工作,并完成设置,我们需要创建高速缓存表“my_table_name”。对于这一点,需要做到以下几点 -
python manage.py createcachetable
caches = { 'default': { 'backend': 'django.core.cache.backends.filebased.filebasedcache', 'location': '/var/tmp/django_cache', } }
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'),)
{% 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个参数 − 想要的块被缓存(秒)以及名称提供给缓存片段。