【问题标题】:problem with flask-restful circular nested resourcesflask-restful 循环嵌套资源的问题
【发布时间】:2019-06-14 16:23:23
【问题描述】:

我在单独的文件中有两个字段要编组。它们是:

from games.controllers.api.categories import category_fields
game_fields = {
    'title': fields.String,
    'developer': fields.String,
    'categories': fields.List(fields.Nested(category_fields)),
    'uri': fields.Url('game')
}

from games.controllers.api.games import game_fields
category_fields = {
    'name': fields.String,
    'games': fields.List(fields.Nested(game_fields)),
    'uri': fields.Url('category')
}

当我运行应用程序时,它会抛出一个错误:

ImportError: cannot import name 'category_fields' from 'games.controllers.api.categories'

显然问题在于循环导入。那我应该怎么解决呢?

顺便说一句:game_fields 中的“开发者”部分显示“<Developer 1>”。当我将其更改为“developer_id”:fields.Integer 时,它可以毫无问题地为我提供开发人员 ID。但我希望它像“开发者”:“EA Sports”。我该怎么做?

【问题讨论】:

    标签: python flask flask-sqlalchemy flask-restful


    【解决方案1】:

    这样的递归结构肯定会给你带来问题,但如果你决定这样做,这是避免循环导入错误的一种可能方法:

    game_fields = {
        'title': fields.String,
        'developer': fields.String,
        'uri': fields.Url('game')
    }
    from games.controllers.api.categories import category_fields
    game_fields['categories'] = fields.List(fields.Nested(category_fields))
    
    category_fields = {
        'name': fields.String,
        'uri': fields.Url('category')
    }
    from games.controllers.api.games import game_fields
    category_fields['games'] = fields.List(fields.Nested(game_fields))
    
    

    至于你的第二个问题,你还没有描述你的 Developer 类的样子。如果您可以控制此类,则可以更改此类将自身呈现为字符串的方式,并使其成为开发人员的名称,而不是 <Developer id>

    【讨论】:

    • 这解决了我的第一个问题。但是关于第二个,你是否建议我创建类似 developer_fields 的东西来编组?
    • 实际上它给了我错误:RecursionError: maximum recursion depth exceeded while calling a Python object。但无论如何,我明白你的意思..
    • 如果您想将Developer 对象呈现为字符串,您需要做的就是在类中添加正确的字符串表示。您似乎将此定义为<Developer :id>。如果您将其更改为开发者名称,您将得到您想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2021-05-17
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    相关资源
    最近更新 更多