我正在制作Flask应用。
我写了这段代码:

from flask import Flask, session
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

@app.route('/my-route')
@cache.cached(timeout=50)
def my_route():
  id = request.args.get('id')
  schema = Schema({
    Required('id'): All(Coerce(str))
})
try:
    schema({'id': id})
except MultipleInvalid as e:
    str(e)

  ans=test(session[‘id’])
  return ans

if __name__ == '__main__':
    app.run(debug=True)
当我运行追加访问localhost:8000/my-route?id=aDj1948时,我得到:RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.错误。
我重写了@cache.cached(timeout=50, key_prefix=make_cache_key),但是发生了同样的错误。我认为我不必在代码中的任何地方设置 secret key ,因此我真的无法理解什么地方出了问题。
我该如何解决?
我的代码有什么问题?

最佳答案

它与缓存无关。为了使用 session ,您必须设置一个 key :http://flask.pocoo.org/docs/1.0/quickstart/#sessions

在初始化 app 后添加以下内容(显然不要使用我的示例并更改 key ):

app = Flask(__name__)

# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

10-01 22:36
查看更多