首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flask-Cache不区分GET和POST

Flask-Cache不区分GET和POST
EN

Stack Overflow用户
提问于 2016-01-29 03:29:51
回答 1查看 939关注 0票数 2

我有一个Flask路由,结构如下:

代码语言:javascript
复制
@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)?

EN

回答 1

Stack Overflow用户

发布于 2016-01-29 10:09:50

是。cache装饰器提供了一个unless kwarg,它接受可调用的。从callable返回True以取消缓存。使用以下命令进行测试:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35070326

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档