12

I was wondering if it is possible to store an object directly in a Flask session, without the need to rewrite the serializer. Are there any functions I need to implement in my class in order to get this working? Sample code that is below. This is what I want it to look like. However, when you try to execute that it throws an error à la TypeError: Object of type 'Test' is not JSON serializable

Any help is greatly appreciated! Thanks in advance! :)

import flask
from flask import Flask, session, redirect

class Test:
    def __init__(self, x, y, z):
    self.x = x
    self.y = y
    self.z = z

app = Flask(__name__)
app.secret_key = 'xyz'

@app.route('/')
def main():
    session['my_object'] = Test(1, 2, 3)
    return redirect('retrieve')

@app.route('/retrieve')
def return_my_object():
    my_object = session.get('my_object')
    return str(my_object)

if __name__ == '__main__':
    app.run(debug=True)
fweidemann14
  • 1,714
  • 3
  • 13
  • 20
  • similar question: https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable – VPfB Aug 08 '17 at 13:53

1 Answers1

10

A simple way to make your object serialize and achieve what you want is to use __dict__ like so:

def main():
    session['my_object'] = Test(1, 2, 3).__dict__
    return redirect('retrieve')
bgse
  • 8,237
  • 2
  • 37
  • 39
  • 1
    I prefer `vars(Test(1, 2, 3))`, over accessing `__dict__` directly, but that's essentially the same. Note that you will also need to deserialize the dictionary to a `Test` object. I recommend adding methods `to_json()` and `from_json()` to the `Test` class and calling them manually. – Sven Marnach Aug 08 '17 at 12:10
  • 1
    thank you guys, working perfectly! ;) – fweidemann14 Aug 08 '17 at 12:20