Either 编写自己的会话序列化器 https://docs.djangoproject.com/en/stable/topics/http/sessions/#write-your-own-serializer允许你序列化datetime
直接对象,或存储datetime
某种其他形式的价值。
如果您想将其保存为秒,请使用datetime.timestamp() method https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp:
request.session[social_ticketing_cookie_name(request.event)] = {
'code': code,
'expiry_date': expiry_date.timestamp()
}
你自己SESSION_SERIALIZER
类只需要提供loads
and dumps
方法,直接类似于json.loads()
and json.dumps()
(这就是如何实现了标准 JSON 序列化器 https://github.com/django/django/blob/a8b03bea180e0660c0e159f3e7cf6192b512925f/django/core/signing.py#L81-L90).
如果你想编码datetime
对象并能够透明地将它们转回datetime
再次对象,我将使用嵌套对象格式将此类值标记为特殊值:
from datetime import datetime
class JSONDateTimeSerializer:
@staticmethod
def _default(ob):
if isinstance(ob, datetime):
return {'__datetime__': ob.isoformat()}
raise TypeError(type(ob))
@staticmethod
def _object_hook(d):
if '__datetime__' in d:
return datetime.fromisoformat(d['__datetime__'])
return d
def dumps(self, obj):
return json.dumps(
obj, separators=(',', ':'), default=self._default
).encode('latin-1')
def loads(self, data):
return json.loads(
data.decode('latin-1'), object_hook=self._object_hook
)
and set SESSION_SERIALIZER
为上述模块的完整限定名称(path.to.module.JSONDateTimeSerializer
).
上面使用的是datetime.fromisoformat() method https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat,Python 3.7 中的新功能。