3

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
  • Did you set the timeout parameter of the cached decorator on purpose? As far as I understand, you don't want the cache to expire between 10:30 and 16:30, right? Commented Mar 11, 2018 at 14:02
  • @DanielRuiz , the timeout cache is use when it is not in the time range, it only access the url link once in 60 seconds. If less than 60 s, it will use cache previously Commented Mar 12, 2018 at 6:32

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

The if path unable to work. It shows [GET]#012Traceback (most recent call last):#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app#012 response = self.full_dispatch_request()#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1361, in full_dispatch_request#012 response = self.make_response(rv)#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1439, in make_response#012 raise ValueError('View function did not return a response')#012ValueError: View function did not return a response in error log

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.