How does CherryPy caching work?

I recently discovered that object attributes in CherryPy persist between requests (and between clients). So I wonder if it makes sense to store page output in such an attribute? Like this:

class Page: def default(self, pagenumber): if pagenumber not in self.validpages: return 'Page number not found' try: html = self.pageoutput[pagenumber] except KeyError: html = self.formatter(self.dbcall(pagenumber)) return html default.exposed = True def formatter(self, data): html = # Formatting code here return html def dbcall(self, pagenumber): data = # Database lookup code here return data 

I know that CherryPy caches GET requests by default. In my tests, when an attribute of an object was part of the result and this attribute was changed, CherryPy served the attribute of the new value. Does this mean that the output was partially cached?

For me, this would be useful if you would update self.pageoutput every time you change the database. The only difficulty I could imagine was if I wanted to display user information. What do you think?

+1
source share
1 answer

CherryPy does not cache GET requests by default; You must explicitly enable the caching tool as described in this documentation.

To answer your first question, yes, this is perfectly true for storing things like "pageoutput" that don't change between calls. However, there are a few caveats:

  • HTTP caching is much better than what you can write yourself. So prefer this for whole answers.
  • Therefore, use special caching for parts of the answers, such as templates and banners, etc.
  • Be very careful to create a secure shared storage. See effbot writeup on this for a start. In general, try to create and save such values โ€‹โ€‹at application startup, if possible, and not during the request; if you write such data in the main thread only at startup, it should be safe to read in multiple threads for each request. If you need such data to change as the state of the application progresses, you probably want to use a database or some other mechanism in which hundreds of man-years of work should make it safe at the same time.
+4
source

All Articles