Python Sql Alchemy - How to jsonify a class object result from a database query
You can use marshallow. Here is the example. define a serializer.py
and put it beside your main.py
file, and:
in serializer.py
from marshmallow import Serializer###### USER SERIALIZER #####class UserSerializer(Serializer): class Meta: # Fields to expose fields = ('username') # you can add any other member of class user in fields#Return the user data in json formatdef get_user_serialized(user): return UserSerializer(user).data
in your main.py
from .serializers import get_user_serialized.........x = db.session.query(User).filter_by(username = request.form['username'], password = request.form['password']).first()serialized = [get_user_serialized(item) for item in x]res = jsonify(res=serialized)return res
With JSON serialize you can do that.
Look this: http://prschmid.blogspot.com/2012/12/json-serializing-sqlalchemy-objects.html
it work for me
I assume the variable '_updated'
& '_created'
in your class User
are of type DateTime. Datetime is not serilzable in jsonify. You can just convert your datetime variable into str. i.e. str(some_date_in_datetimeformat) might work.
Also, '_sa_instance_state'
which is of type sqlalchemy.orm.state.InstanceState should be serializable.
Update:
jsonify is not able to serialize your object. The best solution is to define a function serialize() inside your class and use it to make the data serializable. So your class becomes,
class User(object): def serialize(): return { '_id': 1, 'username': u'WashingtonGeorge' 'fullname': u'George Washington' # other fields that you need in the json }
then at the place where you want to jsonify the data, just call.
jsonify(x.serialize())