【问题标题】:Handling hierarchical URIs with Flask-RESTful使用 Flask-RESTful 处理分层 URI
【发布时间】:2016-01-19 20:02:51
【问题描述】:

我想要一个看起来像这样的 RESTful api:

example.com/teams/
example.com/teams/<team_id>
example.com/teams/<team_id>/players
example.com/teams/<team_id>/players/<player_id>
...
example.com/teams/<team_id>/players/<player_id>/seasons/<season_id>/etc

每个 URI 都可以适当地处理 GET 和可能的 POST。

我希望能够做类似的事情:

class Team(Resource):
    def post(self):
        #Handler for /teams/
    def post(self, team_id):
        #Handler for /teams/team_id
    def post(self, team_id, player_id):
        #Handler for /teams/team_id/players/player_id

并使用:

api.add_resource(Team, '/teams/', 'teams/<team_id>/players/<player_id>')

这不起作用,因为后续的 POST 处理程序会覆盖之前的处理程序。

使用 Flask-RESTful 处理 URL 中变量数量可变(层次结构深度可变)的 API 的正确方法是什么?

【问题讨论】:

    标签: python rest flask flask-restful


    【解决方案1】:

    Python 不支持这种特定方式的方法重载。在您的代码中,您没有重载 post() 函数,而是重新定义

    基本上post() 的最后一个定义很重要,如您所见,它需要 3 个参数:

    class Team(Resource):
        def post(self, team_id, player_id):
            # This is the final definition of post()
            # The definitions above this one do not take effect
    

    否则,使用具有参数默认值的单个方法很容易获得行为:

    class Team(Resource):
        def post(self, team_id=None, player_id=None):
            if team_id is None and player_id is None:
                # first version
            if team_id is not None and player_id is None:
                # second version 
            if team_id is not None and player_id is not None:
                # third version
    

    对于您的 URL,Flask 将为 URL 中未定义的参数传入 None

    【讨论】:

    • 我看到的问题是它无法区分teams/&lt;team_id&gt;/playersteams/&lt;team_id&gt;。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    相关资源
    最近更新 更多