python config_error ai_generated true

运行时错误:未设置密钥导致会话不可用

RuntimeError: The session is unavailable because no secret key was set. Please set the secret key on the application to something unique and secret.

ID: python/flask-session-cookie-not-signed

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-02-01首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

使用会话的Flask应用必须通过`app.secret_key`设置密钥;未设置时,会话操作会抛出运行时错误。

English

Flask applications using sessions must set a secret key via `app.secret_key`; without it, session operations raise a RuntimeError.

generic

解决方案

  1. 100% 成功率
    Set `app.secret_key = 'your-secret-key'` in your app creation code, preferably from environment variables: `import os; app.secret_key = os.environ.get('SECRET_KEY', 'dev-key')`.
  2. 95% 成功率
    If using an app factory, set it in `create_app()` before returning the app.

无效尝试

常见但无效的做法:

  1. 90% 失败

    Setting `app.config['SECRET_KEY']` after the first request doesn't help; it must be set before any session is used.

  2. 95% 失败

    Using an empty string as secret key still raises the error because Flask checks for truthiness.