Python: Flask Cache for a range of time

My Flask app, will get data from an url only from certain time. If it is outside the range of time, it will used the last query data from the url that save in Cache. Outside the range of time, the url will return no data. Thus, I want to reuse the last data in cache

from flask_app import app
from flask import jsonify,abort,make_response,request
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cache import Cache
from datetime import datetime, time

app.config['CACHE_TYPE'] = 'simple'
app.cache = Cache(app)

@app.route('/top', methods=['GET'])
@app.cache.cached(timeout=60)
def top():
    now = datetime.now()
    now_time = now.time()
    if now_time >= time(10,30) and now_time <= time(16,30):
       print "within time, use data save in cache"
       # function that use last data query from url, save in cache
    else:
       page = requests.get('http://www.abvfc.com')
       data = re.findall(r'items:(.*)',page.content)
return jsonify(data)

The problem is I can't get the last Cache data. If there is no access to the api /top in the last 60 seconds, there will be no data.

  1. Cache the data one minutes before the url return no data at 16.30

  2. User can use the cache data outside range of time

I am not familiar with cache, so may be my current idea is not the best way.

2 answers

  • answered 2018-03-11 13:47 sahama

    i am not a flask user but perhaps this is your wanted decorator

    def timed_cache(cache_time:int, nullable:bool=False):
        result = ''
        timeout = 0
        def decorator(function):
            def wrapper(*args, **kwargs):
                nonlocal result
                nonlocal timeout
    
                if timeout <= time.time() or not (nullable or result):
                    result = function(*args, **kwargs)
                    timeout = time.time() + cache_time
    
                return result
            return wrapper
        return decorator
    

  • answered 2018-03-11 15:14 Daniel Ruiz

    Assuming that you only want your cache to be working between 10:30h and 16:30h, I'd change a bit the approach you are using with the cache.

    The problem I see with your current implementation is, apart from the undesirable cache expiration during the critical time range, that you'll also need to disable it at the moments you want to actually return an updated response.

    That said, I'll use a different strategy: saving to cache every time I compute an updated response and retrieving the response from the cache in the critical time period.

    Regarding the Flask-Cache documentation and the information in this tutorial, I'd modify your code as follows:

    from flask_app import app
    from flask import jsonify,abort,make_response,request
    from flask.ext.sqlalchemy import SQLAlchemy
    from flask.ext.cache import Cache
    from datetime import datetime, time
    
    app.config['CACHE_TYPE'] = 'simple'
    app.cache = Cache(app)
    
    
    @app.route('/top', methods=['GET'])
    def top():
        now = datetime.now()
        now_time = now.time()
    
        if now_time >= time(10,30) and now_time <= time(16,30):
            print "within time, use data save in cache"
            return app.cache.get('last_top_response')
    
        page = requests.get('http://www.abvfc.com')
        data = re.findall(r'items:(.*)',page.content)
        response = jsonify(data)
        app.cache.set('last_top_response', response)
        return response
    

    I hope this to suit your needs