我想要一个如下所示的RESTful应用程序接口:
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处理程序会覆盖以前的。
在URL中可能存在可变数量的变量(层次结构的可变深度)的情况下,使用Flask-RESTful处理API的正确方法是什么?
发布于 2016-01-20 04:14:14
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。
https://stackoverflow.com/questions/34885932
复制相似问题