简体   繁体   中英

Python-Flask Json serialize for get operation from database

I use mssql with flask to create a restful api. I have some problems with converting datas as json. The object that i receive has 4 property (for now); Id,Name,Latitude,Longitude I convert them to json like this :

cursor.execute("Select * from Veteriner")
veteriners=[]
for row in cursor:
    veteriners.append({"Id":row[0],"Name":row[1],"Latitude":row[2],"Longitude":row[3]})
return jsonify(veteriners)

But I want to know if there's another dynamic way to convert this object to json object because for example if i add more props in my database every time i have to check every converting by hand..

Try to create a model class for your database table. For example,

class Model:
    def __init__(self, id, name, lat, lon):
        self.id = id
        self.name = name
        self.lat = lat
        self.lon = lon


def yourFunc():
    array = list()
    for row in cursor:
        array.append(Model(row[0], row[1], row[2], row[3]).__dict__)
    return jsonify(array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM