Den 07/08/2014 kl. 08.22 skrev Chen Xu <
xuch...@gmail.com>:
> Hi Everyone,
> I have a dynamic page which generates some data from the database, but the content in the database might be the same for everyone or for a long time, so I wonder what is the best way to cache the page so that it won't be talking to the database every time?
The answer depends on what kind of changes to the data you will encounter. You can cache either client-side or server-side.
If you know in advance when the next update is, or that it at least won't change (or you can accept serving stale data) for the next x seconds (hours, days, weeks), then you can use standard HTTP cache headers to tell the client to cache the content locally.
If you don't know when the next change is, then you can do one of two things;
a) Find a cheap way of detecting data changes by looking at e.g. a timestamp in the database. Then, render the page from scratch if there was a change, or serve a cached version using the Django cache framework if there was no change.
b) Put the fully rendered page in cache server-side using the Django cache framework (or Varnish), and add a hook into the code that updates the database, which invalidates the cache on updates. You can either update the cache eagerly (force a cache insertion after the invalidation) or lazily (when a user requests the page), depending on your needs.
The performance gain will naturally depend on the rate of database updates vs. page requests.
Erik