[Python] Flask and Flask Session, using a ad-hoc decode/encode (eg. with msgpack)

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to explicitly tell to flask-session how to encode / decode some instances from classes that are specific to my application. (This is legacy code, I can not change the classes).

    For example I have some classes looking like this:

    class Subclass(metaclass=abc.ABCMeta):
    def __init__(self, before=None, next=None, nested_steps=None):
    self.before = before
    self.next = next
    self.nested_steps = nested_steps or []


    class MyClass1(Subclass):
    def __init__(self, **kwargs):
    super().__init__(**kwargs)
    self.number = 1
    self.name = "myclass1"

    class MyClass2(Subclass):
    def __init__(self, **kwargs):
    super().__init__(**kwargs)
    self.number = 2
    self.name = "myclass2"
    self.nested_steps = [MyClass1()]

    class OverallClass:
    def __init__(self):
    self.class1 = MyClass1()
    self.class2 = MyClass2(before=self.class1)
    self.class1.next = self.class2
    self.class2.nested_steps = [self.class1]
    self.steps = [self.class1, self.class2]



    I can encode /decode them myself and even use msgpack for this, following the documentation:

    thedict = {"id": 1, "obj": OverallClass()}
    packed = msgpack.packb(thedict, default=encode_internalClass)
    unpacked = msgpack.unpackb(packed, object_hook=decode_internalClass)


    This works fine for standalone serialization and deserialization. However, I am struggling to integrate this with flask_session. I think I need to overwrite the serializer of flask_session to use those encode_internalClass and decode_internalClass within my app and with jinja2 templates.

    I would need this because I am using for example :


    @app.route("/save_object_live")
    def save_object_live():
    # Create an instance of our internal class
    overallclass = OverallClass()
    # Serialize the object and store it in the session
    session["test_local"] = overallclass
    flash("Object saved in session")
    return redirect(url_for("home"))


    @app.route("/load_object_live")
    def load_object_live():
    # Deserialize the object from the session
    serialized_data = session.get("test_local")
    if serialized_data:
    flash("Object loaded from session")
    return redirect(url_for("home"))
    else:
    flash("No object found in session")
    return redirect(url_for("home"))





    The full stack of the application is flask, flask-session, jinja2 and mongodb.

    Continue reading...

Compartilhe esta Página