使用Flask-RESTful处理分层URI

时间:2016-01-19 20:02:51

标签: python rest flask flask-restful

我想要一个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处理API的正确方法是什么,其中URL中可能存在可变数量的变量(层次结构的可变深度)?

1 个答案:

答案 0 :(得分:0)

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

基本上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 的最后一个定义是重要的,它可以看到3个参数:

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

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

None

对于您的网址,Flask会向<select data-bind="options: OptionsCollection, optionsCaption: '--Select One--', optionsValue: 'ValueForOptions', optionsText: 'TextForOptions', value: selectedValue, event:{change: changedFunction}"></select> 传递未在网址中定义的参数。