gpt4 book ai didi

Python Sqlalchemy - 如何将数据库查询的类对象结果 jsonify

转载 作者:太空狗 更新时间:2023-10-29 23:59:07 24 4
gpt4 key购买 nike

基本上,我只想对我的 sql 查询结果进行 json 编码。

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

这是打印 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'WashingtonGeorge@yahoo.com'}

最佳答案

您可以使用棉花糖。这是例子。定义一个 serializer.py 并将其放在 main.py 文件旁边,并且:

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

在你的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

关于Python Sqlalchemy - 如何将数据库查询的类对象结果 jsonify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23600578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com