Problems with extending session "datetime is not JSON serializable"

1.5k views Asked by At

In the view I have:

from datetime import timedelta
from django.utils import timezone

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

but it raises

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

I've found one solution:

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

but it works only in Chrome ... in Safari django raises error

UnpicklingError at / invalid load key, '{'.

Any suggestions?


Workaround #1

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

There are 1 answers

1
suselrd On BEST ANSWER

According to 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.

So, you are getting the expected behavior. If you want to pass a datetime to session.set_expiry, you have to use PickleSerializer. In my opinion, the workaround you proposed, it's actually the best solution, and keep using the JSONSerializer.