从调度程序和用户请求更新FlaskCache

2024-06-26 08:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试缓存一个耗时的请求的结果。在

首先,我有一个烧瓶模板,如下所示:

@app.route("/")
@app.route("/tabs", methods=['GET','POST'])
def tab():
return render_template("tabs.html")

@app.route("/graph", methods=['GET','POST'])
def graph():
#Some code
return render_template("chart.html", the_div=div, the_script=script,
                       form=form, tables=table, titles = testyear)

@app.route("/prices", methods=['GET','POST'])
def prices():
#Some other code
return render_template("prices.html", PlotGroup=PlotGroup, 
ScriptGroup=ScriptGroup, DivGroup=DivGroup)

我已经在代码的顶部初始化了应用程序、缓存和超时:

^{pr2}$

我还创建了一个配置类:

class Config(object):
JOBS = [
    {
        'id' : 'refresh_cache',
        'func' : 'main:get_my_cache',
        'trigger' : 'interval',
        'seconds' : 5
    }
]

SCHEDULER_API_ENABLED = True

函数“get_my_cache()”定义如下:

@app.cache.cached(timeout = CACHE_TIMEOUT, key_prefix='my-cache')
def get_my_cache():
cacheval = app.cache.get('my-cache')
print(cacheval)
if cacheval is None:
    #cacheval1, cacheval2 = DataHandling.extract_full_table()
    cacheval1, cacheval2 = DataHandling.offlinedata()
    cacheval = [cacheval1, cacheval2]
    print("Cache updated at : " + time.strftime("%b %d %Y - %H:%M:%S"))
    app.cache.set('my-cache', [cacheval1, cacheval2])
return cacheval[0], cacheval[1]

在主部分,我加载所有内容:

if __name__ == '__main__':
app.config.from_object(Config())
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()

if IS_PROD:
    app.run(host='0.0.0.0',debug=False, port=5000)
else:
    app.run(debug=True, port=5001)

因此,如果我能从下面的时间表中理解得很好:

None
Cache updated at : Jun 19 2017 - 11:25:58
None
Cache updated at : Jun 19 2017 - 11:26:23
None
Cache updated at : Jun 19 2017 - 11:26:25
127.0.0.1 - - [19/Jun/2017 11:26:25] "GET /graph HTTP/1.1" 200 -
  1. 我的缓存每5秒就会检查一次缓存。

  2. 我的问题是,当我刷新页面时,我看到在最后一次更新2秒后缓存更新。。。根据我的理解,似乎有两种缓存:一种用于页面(localhost/graph),另一种由调度器设置。即使两者都与相同的key_前缀相关。。。

我知道可能和不同的线程有关?会是问题吗?在


Tags: noneappcachegetreturnmydefroute