Skip to main content
 首页 » 编程设计

python之如何限制在 Flask-RestPlus 中使用 fields.list 返回的内容

2025年01月19日10bjzhanghao

每个建筑物都有单元,每个单元都与一个帐户相关联。一个单元可以关联多个帐户。每个单元只能有一个状态为“事件”的帐户。

API 返回所有单元的列表,每个单元中嵌套的是与该单元关联的所有帐户的列表。

如何返回相同的单位列表,但只返回与每个单位相关联的事件帐户?

#model.py 
 
class Unit(db.Model): 
    __tablename__ = 'units' 
    ... 
    building_id = db.Column(db.Integer, db.ForeignKey('buildings.id')) 
    building = db.relationship("Building", back_populates="units") 
    accounts = db.relationship("Account", back_populates="unit") 
 
class Account(db.Model): 
    __tablename__ = 'accounts' 
    id = db.Column(db.Integer, primary_key=True) 
    status = db.Column(sqlalchemy_utils.ChoiceType(STATUS_CHOICES)) 
    ... 
 
#building.py 
 
@api.route('/units') 
class BuildingUnits(Resource): 
    @api.marshal_with(schemas.unit_fields, envelope='data') 
    def get(self): 
        """ Get list of all units 
        """ 
        return rbac.current_identity.building.units 
 
#schemas.py 
 
unit_fields = api.model('unit_fields', { 
    'id': fields.String, 
    ...etc 
    ...etc 
    'accounts': fields.List(fields.Nested(account_fields)), 
}) 
 
account_fields = api.model('account_fields', { 
    'id': fields.String, 
    ...etc 
    ...etc 
    'status': fields.String(attribute=lambda x: getattr(x.status, 'value', 'Inactive')), 
}) 

请您参考如下方法:

在问了某人(我不确定他想让我宣传是谁)之后

他的回复如下:

This is actually a good example why I tend to prefer to not use extensions to handle the API payloads. Sooner or later you find something that you need isn’t directly supported and you end up having to create compromise solutions.

What I would do in your case, is define a @property in your model that is maybe called active_account. This would be implemented as a database query that returns that one account that you want singled out. Then you can add “active_account” to your schema, so that Flask-RESTful renders it as a related item.

Hope this helps.

我认为这是一个很好的答案,它解决了我的问题。

然后我跟进了:

Im not quite sure what you're referring to when you said: "why I tend to prefer to not use extensions to handle the API payloads."

Which extension are you referring to. What exactly would you do to implement what I have without using "extensions"

然后他回答:

You are using Flask-RESTful, that is the extension I was referring to. I really have nothing against Flask-RESTful, works well, but I prefer to write my APIs in straight Flask.

这就是所有人,也许稍后我会发布我是如何实现他所说的内容的。