【发布时间】:2014-01-10 00:02:02
【问题描述】:
在我的 Flask-RESTful API 中,假设我有两个对象,用户和城市。这是一对多的关系。现在,当我创建我的 API 并向其添加资源时,我所能做的似乎就是将非常简单和通用的 URL 映射到它们。这是代码(不包括无用的东西):
class UserAPI(Resource): # The API class that handles a single user
def __init__(self):
# Initialize
def get(self, id):
# GET requests
def put(self, id):
# PUT requests
def delete(self, id):
# DELETE requests
class UserListAPI(Resource): # The API class that handles the whole group of Users
def __init__(self):
def get(self):
def post(self):
api.add_resource(UserAPI, '/api/user/<int:id>', endpoint='user')
api.add_resource(UserListAPI, '/api/users/', endpoint='users')
class CityAPI(Resource):
def __init__(self):
def get(self, id):
def put(self, id):
def delete(self, id):
class CityListAPI(Resource):
def __init__(self):
def get(self):
def post(self):
api.add_resource(CityListAPI, '/api/cities/', endpoint='cities')
api.add_resource(CityAPI, '/api/city/<int:id>', endpoint='city')
如您所见,我可以做任何我想做的事情来实现一个非常基本的功能。我可以 GET、POST、PUT 和 DELETE 两个对象。但是,我的目标有两个:
(1) 能够使用城市名称等其他参数进行请求,而不仅仅是
城市标识。它看起来像:api.add_resource(CityAPI, '/api/city/<string:name>', endpoint='city')
除非它不会给我这个错误:
AssertionError:视图函数映射正在覆盖现有的 端点函数
(2) 能够将两个资源组合在一个请求中。说我想得到所有
与某个城市相关联的用户。在 REST URL 中,它应该类似于:/api/cities/<int:id>/users
我如何用 Flask 做到这一点?我将其映射到哪个端点?
基本上,我正在寻找将我的 API 从基本变为有用的方法。
【问题讨论】:
标签: python flask flask-restful rest