简体   繁体   English

烧瓶不稳定的圆形嵌套资源的问题

[英]problem with flask-restful circular nested resources

I have two fields in separate files to marshal with. 我在单独的文件中有两个字段要编组。 They are: 他们是:

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')
}

and

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

When I run the app it throws me an error: 当我运行该应用程序时,它引发了一个错误:

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

Obviously the problem is with circular imports. 显然问题在于循环进口。 So how should I solve this? 那么我该如何解决呢?

Btw : the 'developer' part in game_fields shows me " <Developer 1> ". 顺便说一句 :game_fields中的“开发人员”部分显示了“ <Developer 1> ”。 And when I change it to "developer_id": fields.Integer, it gives me developer id with no problem. 并且当我将其更改为“ developer_id”:fields.Integer时,它为我提供了开发人员ID毫无问题。 But I want it to be like "developer": "EA Sports". 但我希望它像“开发者”:“ EA Sports”。 How can I do this? 我怎样才能做到这一点?

A recursive structure like this is bound to give you problems, but if you are decided on it, this is one possible way to avoid circular import errors: 这样的递归结构必然会给您带来问题,但是如果您决定采用这种结构,则这是避免循环导入错误的一种可能方法:

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))

As far as your second question, you haven't described what your Developer class looks like. 至于第二个问题,您尚未描述Developer类的外观。 If you have control over this class, you can change how this class renders itself as a string and make it be the name of the developer instead of <Developer id> . 如果您可以控制此类,则可以更改此类以字符串形式呈现的方式,并使其成为开发人员的名称,而不是<Developer id>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM