Basically, I just want to json encode the results of my sql query.
x = db.session.query(User).filter_by(username = request.form['username'], password = request.form['password']).first()
print vars(x)
return jsonify(x)
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: < User WashingtonGeorge> is not JSON serializable
Here is the result for the print vars(x)
{'_updated': None, 'username': u'WashingtonGeorge', 'password': u'Washington', '_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x7fd12a50c8d0>, 'firstname': u'George', 'lastname': u'Washington', '_created': None, 'fullname': u'George Washington', '_id': 1, 'email': u'[email protected]'}
To add a serialization method have all your SQLAlchemy models inherit from an abstract base class. This base class defines the to_dict method that loops through the model's columns and returns a dictionary. def to_dict(self, show=None, _hide=[], _path=None): """Return a dictionary representation of this model."""
It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session. It creates a SQL JOIN against this Query object's criterion and apply generatively, returning the newly resulting Query.
Simple and quick to get going in two steps. from flask_serialize import FlaskSerialize # create a flask-serialize mixin instance from # the factory method `FlaskSerialize` fs_mixin = FlaskSerialize(db) class Item(db. Model, fs_mixin): id = db. Column(db. Integer, primary_key=True) # other fields ...
_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance. While not directly relevant to this section, if we want to get at it, we should use the inspect() function to access it).
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 format
def 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With