Currently, I use functools
' lru_cache
to handle my caching for the function. The problem is that the size of the cache never grows large enough to make use of the LRU
(due to the fact that the function never takes in a parameter). Instead, the function, when called, opens up a specific URL and return its contents.
Is there a way in which I can specify the 'time to live' cache in which after a certain amount of time/certain amount of calls, it refreshes its cache?
The
functools.lru_cache
function accepts amaxsize
argument which saves the results up to themaxsize
most recent calls.You can check this by calling the
cache_info
attribute of your decorated function.If you want to refresh your cache completely you should implement a cash object manually by counting the number of cache calls and resetting the cache whenever it hits the max size.
Demo:
output:
I don't know of a decorator, but you can keep track of the last time you got the page and update as needed. If this is a single-threaded app, it can be simple
You could also age the page with a timer in the background. You need to control access with a lock, but that makes the cache usable in a multithreaded program too.
Finally, the server may include an
Expires: ...
field in the http header. Depending on how well the service was written, this would be a good reflection of how long the page can be cached.