Python 使用Flask RESTful处理分层URI
我想要一个RESTful api,如下所示:Python 使用Flask RESTful处理分层URI,python,rest,flask,flask-restful,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/
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
并使用:
api.add_resource(Team, '/teams/', 'teams/<team_id>/players/<player_id>')
api.add_资源(团队,“/teams/”,“teams//players/”)
这将不起作用,因为后续的POST处理程序将覆盖前一个
使用Flask RESTful处理URL中可能存在变量数量可变(层次结构深度可变)的API的正确方法是什么?Python不支持以这种特定方式进行方法重载。在代码中,您不是在重载post()
函数,而是在重新定义它
基本上,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
否则,使用具有参数默认值的单个方法很容易获得行为:
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
。我看到的问题是,它没有区分团队//players
和团队///code>。有什么想法吗?
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