【问题标题】:Can I sort my SQLAlchemyAutoSchema manually?我可以手动排序我的 SQLAlchemyAutoSchema 吗?
【发布时间】:2021-05-24 05:01:09
【问题描述】:

我刚刚开始在 python 中为我的烧瓶应用程序使用 marshmallow-sqlalchemy 包。一切正常,api 吐出我的数据库的内容,但似乎按字母顺序对字段进行排序,而不是我使用 SQLAlchemy.Model 类创建它们的顺序。现在我想知道是否有办法禁止这样做,或者至少以某种方式手动对字段进行排序?

这就是我创建数据库表的方式:

class Product(db.Model):
    p_id = db.Column(db.Integer, primary_key=True)
    p_name = db.Column(db.String(100), nullable=False)
    p_type = db.Column(db.String, nullable=False)
    p_size = db.Column(db.Integer, nullable=False)
    p_color = db.Column(db.String, nullable=False)

    def __repr__(self):
        return f"Product(name={self.p_name}, type={self.p_type}, size={self.p_size}, color={self.p_color})"

这是我的架构:

class ProductSchema(SQLAlchemyAutoSchema):
    class Meta:
        ordered = True     #I have read about this property on another post, but doesn't do anything here
        model = Product

我的函数以 json 格式返回内容:

    def get(self, id):
        if id:
            product = Product.query.filter_by(p_id=id).first()
            if product:
                product_schema = ProductSchema()
                output = product_schema.dump(product)
            else:
                abort(Response('product not found', 400))
        else:
            products = Product.query.all()
            products_schema = ProductSchema(many=True)
            output = products_schema.dump(products)
        return jsonify(output), 200

Aa 和我得到的输出(按字母顺序排序):

[
  {
    "p_color": "test color1", 
    "p_id": 1, 
    "p_name": "test name1", 
    "p_size": 8, 
    "p_type": "test type1"
  }, 
  {
    "p_color": "test color2", 
    "p_id": 2, 
    "p_name": "test name2", 
    "p_size": 8, 
    "p_type": "test type2"
  }, 
  {
    "p_color": "test color3", 
    "p_id": 3, 
    "p_name": "test name3", 
    "p_size": 8, 
    "p_type": "test type3"
  }, 
  {
    "p_color": "test color4", 
    "p_id": 4, 
    "p_name": "test name4", 
    "p_size": 8, 
    "p_type": "test type4"
  }
]

如上所述,我的应用程序功能齐全。但我至少想知道发生了什么。因此,我们非常感谢您的帮助!

【问题讨论】:

    标签: python flask flask-sqlalchemy marshmallow


    【解决方案1】:

    默认情况下,Flask 在转储 json 输出时对键进行排序。这样做是为了使顺序是确定性的,从而允许计算哈希等。

    the docs

    您可以使用JSON_SORT_KEYS 参数禁用此功能。

    如果您想调试 marshallow 部分,只需在视图函数中打印转储 (output)。

    除非你有充分的理由强制输出顺序,否则你最好还是放手。

    注意:在 flask-smorest 中,我不介意负载在响应中按字母顺序排列,但我喜欢在发布 OpenAPI 规范文件时对其进行排序,因此我不会修改 JSON_SORT_KEYS 和服务于规范文件,I don't use jsonify but raw json.dumps

    【讨论】:

    • 谢谢!我专注于寻找答案的错误包......这有帮助!
    猜你喜欢
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 2013-07-25
    • 2021-09-08
    相关资源
    最近更新 更多