延长会话的问题 "datetime is not JSON serializable"

Problems with extending session "datetime is not JSON serializable"

在我看来:

from datetime import timedelta
from django.utils import timezone

now = timezone.now()
self.request.session.set_expiry(now + timedelta(days=365))

但它提高了

datetime.datetime(2016, 6, 24, 17, 19, 0, 826661, tzinfo=) is not JSON serializable

我找到了一个解决方案:

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

但它只适用于 Chrome ...在 Safari 中 django 引发错误

UnpicklingError at / invalid load key, '{'.

有什么建议吗?


解决方法 #1

self.request.session.set_expiry(int(timedelta(days=365).total_seconds()))

根据Django documentation

set_expiry(value)

Sets the expiration time for the session. You can pass a number of different values:

  • If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes.
  • If value is a datetime or timedelta object, the session will expire at that specific date/time. Note that datetime and timedelta values are only serializable if you are using the PickleSerializer.
  • If value is 0, the user’s session cookie will expire when the user’s Web browser is closed.
  • If value is None, the session reverts to using the global session expiry policy.

因此,您得到了预期的行为。如果要将日期时间传递给 session.set_expiry,则必须使用 PickleSerializer。 在我看来,您提出的解决方法实际上是最好的解决方案,并继续使用 JSONSerializer。