Basically I need to know whether I can use @functools.cached_property in a Flask-RESTPlus Resource subclass to cache an expensive operation or collaborator construction that should not survive beyond a single request.
I'm thinking there are two possibilities:
- A
Resourcesubclass instance is created fresh for each HTTP request routed to that resource. - A
Resourcesubclass instance is created once when an API is constructed and reused for every request routed to that resource for the lifetime of the API.
Caching on the object/instance would only work in Case 1. @cached_property is in effect a lazyily-computed instance variable, its value computed on first use and stored in an instance variable, then served from that variable on each successive access/call. I expect the mechanism is actually a descriptor, but the concept is the same.
In any case, I need a different value for each request, I just need to use it multiple times in the course of processing a single request and I need the value to be computed exactly once for that request.
Will @cached_property work the way I need on a Flask-RESTPlus Resource subclass?
An instance of the
Resourceclass is created for each request. You can quickly verify by creating a breakpoint in its__init__()method.Also, consider using the Flask.g namespace object. It has the lifetime of a request context and is typically used to store db connections, etc that need to be created once per request and destroyed after the request ends.