从调度程序和用户请求中更新Flask-Cache

3
我正在尝试缓存一个耗时请求的结果。
首先,我有一个Flask模板,如下所示:
@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)

我在代码的顶部初始化了应用程序、缓存和超时时间:
# Checking is prod to change server from 5000 to 5001
IS_PROD = sys.argv[1] == "prod"
# Setting up cache timer
CACHE_TIMEOUT = 20
# Defining the Flask App
app = Flask(__name__, template_folder='Template')
# define the cache config :
app.config['CACHE_TYPE'] = 'simple'
app.cache = Cache(app)

我还创建了一个配置类:

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 -

我的调度器每5秒检查一次缓存(时间是为了测试,在实际情况下会更长),我看到每25秒有效地更新一次缓存。
我的问题是,当我刷新页面时,我在上次更新后的2秒钟内看到了缓存更新... 从我的理解来看,似乎有两种缓存:一个是页面(localhost/graph)的缓存,另一个是由调度器设置的缓存。即使两者都与相同的key_prefix相关...
我明白这可能与不同的线程有关?这可能是问题吗?

我已经尝试了一些不同的缓存选项,现在我正在使用TTLCache(在cachetools包中)。我真的看到了线程问题。APSheduler正在使用Thread-1到Thread-10,而Flask正在主线程上运行。然后我将缓存更改为“全局缓存”,但没有解决问题。 - Charles
1个回答

0
def task1(app):
with app.app_context():
    #cache.set("t1","123")
    x=cache.get("t1")
    print(x)

class Config(object):
JOBS = [ {  # add task1
        'id': 'job1',
        'func': '__main__:task1',
        'args': (3, 4,app),
        'trigger': 'interval',
        'seconds': 5,
    }]

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