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-must-be-set

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2025-04-08First Seen

Version Compatibility

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

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Committed secret leaks; session forgery risk.

  2. 90% fail

    Rotates key each request; sessions invalidate immediately.