registering a new serializer for sessions

Hello,

I am attempting to save an object to the session (request.session['key'] = o) however I am getting the error TypeError: Object of type o is not JSON serializable. So I have written a custom encoder (do I also need to write a custom decoder?) however is there a way I can register it with django? Or should I be doing request.session['key'] = serialize(o) and then o = deserialize(request.session['key'])?

Thanks!
Ryan

Django’s sessions serializer is deliberately simple, to prevent security problems: https://github.com/django/django/blob/8725d04764e3528cbaefd0925501f8403d22ae3e/django/core/signing.py#L81

You could implement your own serializer copying this logic and swapping in your JSON encoder/decoder for the calls. However it might be better to use individual functions specifically on the key that contains your special object. Or reconsider your design - sessions shouldn’t normally need to contain complicated data.

Hm I see, the data itself is very simple - it boils down to a string or two and an int haha, so it was very much just a convenience thing to not have to constantly call the specific serialization/deserialization functions. What you linked looks promising though - where would I swap in my own JSON encoder?

I took a look at django.core.serializers but it appears that the register_serializer method expects a module with a Serializer and Deserializer and deals with ORM objects mostly, so I don’t think this is the right place.

There’s a section all about this: https://docs.djangoproject.com/en/3.0/topics/http/sessions/#custom-serializers

This is the setting: https://docs.djangoproject.com/en/3.0/ref/settings/#session-serializer

1 Like

Awesome! Thanks for pointing it out, I couldn’t for the life of me find it!
Best,
Ryan