python - 如何在Python中比较sql和json

标签 python sqlalchemy marshmallow

我遇到以下问题。 我有一个类 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/

相关文章:

sqlalchemy - 如何删除Airflow中的所有用户?

python - 在 Python 和 Marshmallow 中嵌套数据库中不存在的字段

python - 在 python 中绘制二元 3D 矩阵

python - WSGI 作为 AuthFormProvider

python - Keras( tensorflow 后端)获取 "TypeError: unhashable type: ' Dimension'"

python - SQLAlchemy 中的关系未按预期工作

python - 我很难按值对字典进行排序

mysql - python.3类型错误: embedded NUL character

python - 如何在棉花糖中设置 Int 字段的下限

python - 编写 Python POO。棉花糖或原生 Python。创建类的最佳方式是什么?