3

I have a Flask app which does some external API calls and combines this data.

The external API call can take up to ~40 seconds.

Currently I cache the result using flask_caching with an expiry time of 1 hour.

@app.route('/api/pos')
@cache.cached(timeout=3600)
def get_pos():
    return jsonify( [LONG TIME API CALL] )

How do I make flask automatically do the external API call when it's caches expires, as to refresh the cache? Instead of the user having to wait 40 seconds when the cache expired.

I was thinking about a Crob job which calls my flask app every 1 hour with for example cUrl. But there has to be a prettier method.

So to summarize: is there some kind of event which can trigger when flasks cache times out?

Best regards, sorry for my formulation of the question as English is not my native language.

Frank
  • 99
  • 1
  • 6
  • If you're using redis as the backend you can use events as described here: https://stackoverflow.com/questions/61949737/flask-caching-call-back-event-when-key-delete-automatically – John Nov 14 '20 at 13:42
  • I have a similar use case, what did you end up going with? The cron job? – Tyler Chong Jan 07 '22 at 07:48
  • 1
    @TylerChong Yeah I created a Flask CLI command `scheduled()` which is called by the cron job. This scheduled function sets the cache: `cache.set('parts', parts(), timeout=86400)`. – Frank Jan 08 '22 at 11:05

0 Answers0