I have been setting up caching in Django using a database cache. There are two settings TIMEOUT and CACHE_MIDDLEWARE_SECONDS that control how long a page is cached for. What is the difference between these two settings?
相关问题
- Django __str__ returned non-string (type NoneType)
- Django & Amazon SES SMTP. Cannot send email
- Django check user group permissions
- Django restrict pages to certain users
- UnicodeEncodeError with attach_file on EmailMessag
相关文章
- Profiling Django with PyCharm
- Why doesn't Django enforce my unique_together
- MultiValueDictKeyError in Django admin
- Django/Heroku: FATAL: too many connections for rol
- Django is sooo slow? errno 32 broken pipe? dcramer
- Django: Replacement for the default ManyToMany Wid
- Upgrading transaction.commit_manually() to Django
- UnicodeEncodeError when saving ImageField containi
I had the same question and the existing answers still didn't clear it up for me. So I decided to dive into the source code. Yay for open source!
CACHE_MIDDLEWARE_SECONDS
gets used by theUpdateCacheMiddleware
middleware. It sets theCache-Control
(max-age
) header to the value ofCACHE_MIDDLEWARE_SECONDS
if the view didn't already set it, affecting the client-side cache. Here's the code:(Note that I'm cutting out some code and edge-corners to make this quicker to read, you can read the full source code yourself of course.)
It also saves the response in the server-side cache, using the same timeout value which originates from
MIDDLEWARE_CACHE_SECONDS
, overriding theTIMEOUT
setting if it had been set: (context)The middleware
FetchFromCacheMiddleware
goes withUpdateCacheMiddleware
, and it uses the server-side cache values set by the latter, so it is indirectly affected byCACHE_MIDDLEWARE_SECONDS
.The alternative middleware
CacheMiddleware
also usesCACHE_MIDDLEWARE_SECONDS
. This shouldn't affect you unless you're usingCacheMiddleware
.So what's the point of the
TIMEOUT
setting? I suppose it's the default value that's used if you're writing to the cache directly, but it isn't used by the previously mentioned middleware. For example:Indeed the respective documentation does not adequately explain the differences.
The first option,
CACHES
:TIMEOUT
is introduced in Django cache framework, Cache arguments. It is the default expiration time that is used in functions such ascache.set()
, if none else is provided. This is later documented in the low-level cache API usage.The latter,
CACHE_MIDDLEWARE_SECONDS
is introduced in Django cache framework, The per-site cache. Therefore it might be safe to assume that it is the default expiration time for all pages, as if the@cache_page(settings.CACHE_MIDDLEWARE_SECONDS)
would have been used on a per-view basis.According to http://www.djangobook.com/en/2.0/chapter15.html, TIMEOUT is the timeout for connecting to the cache backend and CACHE_MIDDLEWARE_SECONDS is the number of seconds to cache a page. So TIMEOUT is not necessarily useful for all backends.