How Can I Store Objects in a Cookie with Flask

Pretty straightforward: I want to store a custom class that I have created within a Cookie using Flask. I have already set up the thing that adds the cookie, but it doesn’t work due to it’s value being an object?

1 Like

I don’t know much about flask, but according to docs the key and value have to be strings.
So a way to implement the value for your class is to just convert it to string using repr(), but make sure your __repr__ implementation allows you to reconstruct the object. Dataclasses are an easy way.
Maybe you could also use the items of the __dict__ and convert the values to string if needed.

1 Like

This object is coming from a library so I do not think I can directly edit it.

Can you possibly send the Repl link?

I just invited you, check your notifications. Feel free to fix it when you have a chance.

1 Like

Okay, then you can create a function that converts it to a string, such as by using its __dict__ if possible. Use json library to decode cookie. You can also store separate attributes in __dict__ as separate cookies maybe. Even if it has __slots__ instead, you can extract the attribute key-value pairs manually.

import pickle
from flask import Flask, request, make_response

app = Flask(__name)

class CustomObject:
    def __init__(self, data): = data

custom_obj = CustomObject("Some data")
serialized_obj = pickle.dumps(custom_obj)

def set_cookie():
    response = make_response('Cookie set')
    response.set_cookie('custom_data', serialized_obj)
    return response

if __name__ == '__main__':
1 Like