Skip to main content
 首页 » 编程设计

Python:Flask 缓存一段时间

2024年09月07日7cloudgamer

我的 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 分 url 返回无数据前一分钟缓存数据

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

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

请您参考如下方法:

我不是 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