python type_error ai_generated true

TypeError: Object of type datetime is not JSON serializable

ID: python/flask-session-serialization-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-08-15First Seen

Version Compatibility

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

Root Cause

Storing non-JSON-serializable values (datetime, Decimal, custom classes) in the Flask session cookie.

generic

中文

在Flask会话cookie中存储不可JSON序列化的值(datetime、Decimal、自定义类)。

Workarounds

  1. 95% success
    session['ts'] = dt.isoformat()\n# read back: datetime.fromisoformat(session['ts'])
  2. 90% success
    app.config['SESSION_TYPE'] = 'redis'\nSession(app)

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Unrelated to serialization.

  2. 90% fail

    Only affects expiry, not encoding.