python type_error ai_generated true

TypeError: datetime类型的对象无法进行JSON序列化

TypeError: Object of type datetime is not JSON serializable

ID: python/flask-session-serialization-error

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

版本兼容性

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

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 95% 失败

    Unrelated to serialization.

  2. 90% 失败

    Only affects expiry, not encoding.