2

次のような構造の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 のキャッシュのみ)?

4

1 に答える 1

0

はい。cacheデコレーターは、unlesscallable を受け入れる kwarg を提供します。Truecallable から戻り、キャッシングをキャンセルします。次の方法でテストします。

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)
于 2016-01-29T02:09:49.550 に答える