python config_error ai_generated true

RuntimeError: 会话不可用,因为未设置密钥。请为应用设置唯一且保密的 secret_key。

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

ID: python/flask-secret-key-must-be-set

其他格式: JSON · Markdown 中文 · English
80%修复率
89%置信度
0证据数
2025-04-08首次发现

版本兼容性

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

根因分析

app.secret_key 为 None 或空,但 session、flash 或 CSRF(Flask-WTF)需要签名。

English

app.secret_key is None/empty, but session, flash, or CSRF (Flask-WTF) requires signing.

generic

解决方案

  1. 95% 成功率
    app.config['SECRET_KEY'] = os.environ['FLASK_SECRET_KEY']  # set a 32+ byte random value in env
  2. 90% 成功率
    Generate once: `python -c 'import secrets; print(secrets.token_hex(32))'` and store in .env / secrets manager.

无效尝试

常见但无效的做法:

  1. 95% 失败

    Committed secret leaks; session forgery risk.

  2. 90% 失败

    Rotates key each request; sessions invalidate immediately.