Rectangle 27 0

python Fixing the class to enable object storing in Flask session?


from flask.json import JSONEncoder

class CustomJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Passport):
            # Implement code to convert Passport object to a dict
            return passport_dict
        else:
            JSONEncoder.default(self, obj)

# Now tell Flask to use the custom class
app.json_encoder = CustomJSONEncoder

Here is how it would roughly work:

I get "itsdangerous.BadPayload" error (BadPayload: Could not load the payload because an exception occurred on unserializing the data). It doesn't help too much in understanding what's wrong.

I haven't done that myself, but according to the Flask API docs setting app.json_decoder to a sublass of flask.json.JSONDecoder should do the trick. What's the precise problem that you have with that?

Put an import pdb; pdb.set_trace() inside your deserialization code to find out what is going wrong, looks like you have an error in your deserializer. Maybe also enable debug logging.

Thanks, this does one half of it. However, for complete solution, I need to hook also decoding. I've found some example how to do it, but it's not Flask-related. I've already found that doing app.json_decoder = CustomJSONDecoder doesn't do the trick.

That didn't cause any change in the debug output. The error is not triggered in my code, it's somewhere deeper, in itsdangerous.py. I am starting to feel that hooking up custom JSONEncoder and JSONDecoder is not the right way to live. I think I'll put the code that wraps the passport data encoding/decoding in session variable in a separate class that lives in the application scope and connects to the session when necessary.

You have to create a custom JSONEncoder class and tell Flask to use this for JSON serialization/deserialization.

Note