我有一个Flask路由,结构如下:
@app.route('/rootpath1/<path:path>')
@app.route('/rootpath2/<path:path>', methods=['GET', 'POST'])
@cache.cached()
def rootpath():
...对于给定的页面,到“/rootpath2/”的POST通常从缓存中检索(当存在缓存值时),这通常是最后一个GET请求。
例如,用户访问“/rootpath2/myform”,填写表单,然后提交表单。表单将发布到“/rootpath2/myform”,用户将返回到相同的URI,并显示一条消息,指示表单提交成功(如果提交成功,则会发生错误)。
这里的问题是GET总是在POST之前,POST总是触发缓存命中并返回该值。
Flask-Cache有没有办法区分GET和POST,并根据它们进行处理(只缓存GET)?
发布于 2016-01-29 10:09:50
是。cache装饰器提供了一个unless kwarg,它接受可调用的。从callable返回True以取消缓存。使用以下命令进行测试:
from flask import Flask, request, render_template_string
from flask.ext.cache import Cache
app = Flask('foo')
cache = Cache(app,config={'CACHE_TYPE': 'simple'})
t = '<form action="/" method="POST">{{request.form.dob}}<input name="dob" type="date" value={{request.form.dob}} /><button>Go</button></form>'
def only_cache_get(*args, **kwargs):
if request.method == 'GET':
return False
return True
@app.route('/', methods=['GET', 'POST'])
@cache.cached(timeout=100, unless=only_cache_get)
def home():
if request.method == 'GET':
print('GET is not cached')
return render_template_string(t)
if request.method == 'POST':
print('POST is not cached')
return render_template_string(t)
app.run(debug=True)https://stackoverflow.com/questions/35070326
复制相似问题