Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sql Alchemy - How to jsonify a class object result from a database query

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]'}
like image 992
olleh Avatar asked May 12 '14 03:05

olleh


People also ask

How do you serialize a SQLAlchemy model?

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."""

What does SQLAlchemy query return?

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.

How do you serialize an object in flask?

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 ...

What is _sa_instance_state in SQLAlchemy?

_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).


2 Answers

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
like image 126
Nima Soroush Avatar answered Oct 10 '22 02:10

Nima Soroush


With JSON serialize you can do that.

Look this: http://prschmid.blogspot.com/2012/12/json-serializing-sqlalchemy-objects.html

it work for me

like image 45
yograterol Avatar answered Oct 10 '22 00:10

yograterol