python config_error ai_generated true

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-not-set

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-02-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —
3.x active — — —

Root Cause

`app.secret_key` was never configured, so Flask cannot sign session cookies.

generic

中文

未配置 `app.secret_key`,Flask 无法对会话 Cookie 进行签名。

Workarounds

  1. 97% success
    import os
    app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
  2. 95% success
    import secrets
    app.config['SECRET_KEY'] = secrets.token_hex(32)

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Hard-coded weak key leaks via git and is insecure in production.

  2. 95% fail

    Cookie secure flag is unrelated to key availability.