Categories
Python Answers

How to jsonify a SQLAlchemy result set in Python Flask?

Spread the love

Sometimes, we want to jsonify a SQLAlchemy result set in Python Flask.

In this article, we’ll look at how to jsonify a SQLAlchemy result set in Python Flask.

How to jsonify a SQLAlchemy result set in Python Flask?

To jsonify a SQLAlchemy result set in Python Flask, we create our own serialize class.

For instance, we write

from sqlalchemy.inspection import inspect

class Serializer(object):

    def serialize(self):
        return {c: getattr(self, c) for c in inspect(self).attrs.keys()}

    @staticmethod
    def serialize_list(l):
        return [m.serialize() for m in l]

to create a Serializer class that has the static serialize_list method.

Then we use it in our model class by writing

class User(db.Model, Serializer):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String)
    password = db.Column(db.String)

    # ...

    def serialize(self):
        d = Serializer.serialize(self)
        del d['password']
        return d

We call Serializer.serialize with the self User model instance to return a dict that we can return as JSON.

Conclusion

To jsonify a SQLAlchemy result set in Python Flask, we create our own serialize class.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *