我遇到以下问题。
我有一个类 User
简化示例:
class User:
def __init__(self, name, lastname, status, id=None):
self.id = id
self.name = name
self.lastname = lastname
self.status = status
def set_status(self,status)
# call to the api to change status
def get_data_from_db_by_id(self)
# select data from db where id = self.id
def __eq__(self, other):
if not isinstance(other, User):
return NotImplemented
return (self.id, self.name, self.lastname, self.status) == \
(other.id, other.name, other.lastname, other.status)
我有一个像这样的数据库结构:
id, name, lastname, status
1, Alex, Brown, free
以及来自 API 的 json 响应:
{
"id": 1,
"name": "Alex",
"lastname": "Brown",
"status": "Sleeping"
}
我的问题是:
比较 json 与 sql 响应的最佳方法是什么?
做什么的? - 它仅用于测试目的 - 我必须检查 API 是否已正确更改数据库。
如何将 Json 和 DB 结果反序列化到同一个类?有什么常见/最佳实践吗?
目前,我尝试使用 marshmallow
来处理 json,使用 sqlalchemy
来处理 DB,但没有成功。
最佳答案
将数据库行转换为字典:
def row2dict(row):
d = {}
for column in row.__table__.columns:
d[column.name] = str(getattr(row, column.name))
return d
然后将json字符串转换为字典:
d2 = json.loads(json_response)
最后比较一下:
d2 == d
关于python - 如何在Python中比较sql和json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56149772/