Python:Flask缓存一段时间

3

我的 Flask 应用将仅从特定时间的 URL 获取数据。如果超出时间范围,它将使用保存在缓存中的 URL 的最后一个查询数据。超出时间范围,URL 将不返回任何数据。因此,我希望重用缓存中的最后一个数据。

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)

问题在于我无法获取最新的缓存数据。如果在过去60秒内没有访问/api/top接口,那么就不会有数据。

  1. 在16:30返回无数据之前,将数据缓存一分钟

  2. 用户可以在时间范围外使用缓存数据

我对缓存不太熟悉,所以我的想法可能不是最好的方法。


你有意设置了cached装饰器的timeout参数吗?据我所知,你不希望缓存在10:30至16:30之间过期,对吗? - Daniel Ruiz
@DanielRuiz,超时缓存用于在不在时间范围内时,仅在60秒内访问URL链接一次。如果少于60秒,则使用先前的缓存。 - bkcollection
2个回答

1
我不是 Flask 用户,但也许这是你想要的装饰器。
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

1
假设您只想在10:30到16:30之间使用缓存,我会稍微改变您使用缓存的方法。我看到您当前实现的问题是,在关键时间范围内不希望缓存过期,但您还需要在要返回更新响应的时候禁用它。因此,我将使用不同的策略:每次计算更新响应时都保存到缓存中,并在关键时间段从缓存中检索响应。根据Flask-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'])
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

我希望这符合您的需求。

if路径无法工作。在错误日志中显示[GET]#012Traceback(most recent call last):#012 File“/usr/local/lib/python2.7/dist-packages/flask/app.py”,line 1687,在wsgi_app中:#012 response = self.full_dispatch_request()#012 File“/usr/local/lib/python2.7/dist-packages/flask/app.py”,line 1361,在full_dispatch_request中:#012 response = self.make_response(rv)#012 File“/usr/local/lib/python2.7/dist-packages/flask/app.py”,line 1439,在make_response中:#012 raise ValueError('View function did not return a response')#012ValueError:视图函数没有返回响应 - bkcollection

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接