How to serialize SqlAlchemy result to JSON?

后端 未结 27 1521
说谎
说谎 2020-11-22 09:59

Django has some good automatic serialization of ORM models returned from DB to JSON format.

How to serialize SQLAlchemy query result to JSON format?

I tried

27条回答
  •  心在旅途
    2020-11-22 10:29

    You can use introspection of SqlAlchemy as this :

    mysql = SQLAlchemy()
    from sqlalchemy import inspect
    
    class Contacts(mysql.Model):  
        __tablename__ = 'CONTACTS'
        id = mysql.Column(mysql.Integer, primary_key=True)
        first_name = mysql.Column(mysql.String(128), nullable=False)
        last_name = mysql.Column(mysql.String(128), nullable=False)
        phone = mysql.Column(mysql.String(128), nullable=False)
        email = mysql.Column(mysql.String(128), nullable=False)
        street = mysql.Column(mysql.String(128), nullable=False)
        zip_code = mysql.Column(mysql.String(128), nullable=False)
        city = mysql.Column(mysql.String(128), nullable=False)
        def toDict(self):
            return { c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs }
    
    @app.route('/contacts',methods=['GET'])
    def getContacts():
        contacts = Contacts.query.all()
        contactsArr = []
        for contact in contacts:
            contactsArr.append(contact.toDict()) 
        return jsonify(contactsArr)
    
    @app.route('/contacts/',methods=['GET'])
    def getContact(id):
        contact = Contacts.query.get(id)
        return jsonify(contact.toDict())
    

    Get inspired from an answer here : Convert sqlalchemy row object to python dict

提交回复
热议问题