StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 15 · Caching

Cached Expensive View

mediumDjango CachingCaching—No data yet

Problem statement

In this Django project, stop the sales report from recomputing itself on every hit. The page is on a wall-mounted dashboard that reloads every few seconds, and each reload walks the whole sales table one row at a time, while the table itself changes a few times a day at most. The aggregation is given and correct; what is missing is anything that remembers the page it produced.

Requirements

Implement:

  • the response caching on sales_report in app/views.py

Only app/views.py changes. app/models.py, app/reports.py, app/urls.py, the template and the template tag are all given and read-only. sales_report is already written and already renders the right page: it reads the optional region query string, calls compute_sales_summary(region) and renders app/sales_report.html with the figures under the context name summary. Keep that context name and that template; the page is compared element by element. The route is named sales-report and lives at /reports/sales/, where ?region=north scopes the figures to one region and no query string reports every region together.

compute_sales_summary(region=None) in app/reports.py is the expensive path, and it appends one entry to the module-level list COMPUTE_CALLS on every run. The given template carries {% count_render %} from _app/templatetags/report_tags.py_, which appends to a second list, PAGE_RENDERS, on every render. The tests read both lists, because two identical bodies prove nothing: the same figures render the same page whether the work was skipped or done all over again.

The cache is configured in project/settings.py, which is read-only: a single default alias on django.core.cache.backends.locmem.LocMemCache with LOCATION "sales-reports", and SALES_REPORT_CACHE_SECONDS = 2. That setting is the window, and it is short because the tests prove the expiry by waiting out real time rather than by pretending the clock moved.

1. A repeat request inside the window

  • A second request for the same URL within the window comes back 200 with the same page the first request got, including the same serial.
  • compute_sales_summary does not run again, so COMPUTE_CALLS does not grow.
  • The page is not rendered again either, so PAGE_RENDERS does not grow. What is stored has to be the view's own response, not a value from inside the view body that the page is then rebuilt from.
  • The stored page belongs to the URL rather than to one client, so a second visitor asking for the same URL inside the window is served the identical body without any recomputation.

2. The window and its expiry

  • The window is settings.SALES_REPORT_CACHE_SECONDS, read from settings rather than written into the view as a literal.
  • More than that many seconds after a response was stored, the next request runs the aggregation again and renders the figures it returns, so a third request after a sleep past the window shows serial of 2.
  • A window longer than the setting fails that third request.

3. Separate entries per query string

  • /reports/sales/?region=north, /reports/sales/?region=south and /reports/sales/ are three independent entries, each showing its own scope, orders, total and leading product.
  • Storing one leaves the others as they were: after north is cached and south is asked for, asking for north again is still a cache hit and still the north page, byte for byte.
  • The same holds the other way round, so caching a region page never lets the unscoped URL be answered from it or force it to recompute.

Notes

  • Django's page-level cache keys its entries off the full request URI, which includes the query string, and each entry expires on its own clock.
  • The cache only applies where it is applied: wrapping a helper the view calls still runs the view, and caching inside the view body means the body ran.
  • Do not re-implement the aggregation and do not edit app/reports.py; the tests count its calls.
  • The timeout is in seconds, and nothing has to notice an entry expired or clear one by hand.
  • Nothing outside requirements.txt, and no second cache backend: CACHES is configured and read-only.

More in Caching

See the module
Low-Level Cache AsideOne hot price lookup hammers the database from two different pages, and each caller either invented its own caching or did without. Centralize the lookup in a cache-aside helper that reads the cache, computes and stores on a miss under the documented key and timeout, and drops a product's entry whenever a price change or a delete makes it wrong.—No data yetmediumFragment Cached SidebarEvery category page recomputes an expensive trending sidebar on every single request, while the rest of the page has to stay dynamic and must not be cached. Cache just the sidebar with a template fragment keyed by the category slug, leaving everything around it rendered per request.—No data yetmediumLayered Store CachingThe storefront caches nothing: the product page rebuilds itself on every hit, the catalogue pays for every product's facts on every render, and a price change walks away leaving the figures it just made wrong on display. Put a page cache on the product page, a cache-aside helper behind every facts read and a cached fragment around each trending row, all keyed by product id, and make a price change drop exactly that product's three entries.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.