0

我创建了一个烧瓶 Web API 来访问来自 postgresDB 的数据。用于flask_sqlalchemy创建数据库模型,例如

class results(db.Model):
    __tablename__ = 'resultstable'
    id = db.Column(db.Integer, primary_key=True)
    time_stamp = db.Column(db.DateTime, index=True, default=datetime.utcnow())
    name = db.Column(db.String)
    stats = db.Column(JSONB)

并使用flask_marshmallow,添加了对将结果类的实例序列化为 JSON 数据、反序列化 JSON 数据并从中创建结果类实例的支持


class resultsSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = results
        sqla_session = db.session

我为从结果表中获取一行而创建的端点:

def read(Id:int):
    result_exist = (results.query.filter(results.id == Id).one_or_none()
    if result_exist is not None:
        # Serialize the data for the response
        schema = resultsSchema()
        data = schema.dump(result_exist)
        return data
    else:
        abort(
            404,
            f"id:{Id} not found in the table",
        )

我收到以下回复:

{
  "id": 1,
  "name": "ase",
  "stats": "{\n    \"error\": \"make sure to include the columns\"\n}",
  "time_stamp": "2021-03-10T22:29:02.603930"
}

问题是我JSONB在示例stats列中声明的列没有序列化为纯 JSON。我将如何实现它?

期望的结果是:

{
  "id": 1,
  "name": "ase",
  "stats": {
    "error": "make sure to include the columns"
  },
  "time_stamp": "2021-03-10T22:29:02.603930"
}

仅供参考,其他列,例如db.Column(db.ARRAY(db.Float)))正在序列化,但不是db.Column(JSONB))

json.dumps(json.loads(result_exist.stats))在获得诸如or 之类的 python 对象后,我尝试使用简单的序列化 json.dumps(json.loads(data['stats'])),但它只是清除了额外的空格而不是分隔符。

"{\n    \"error\": \"Please make sure to include the columns\"\n}"
 "{\"error\": \"Please make sure to include the columns\"}"

有没有不使用字符串操作但使用flask_marshmallow or来解决问题的标准方法marshmallow

4

0 回答 0