以下让我感到不雅但是有效。有没有办法让使用相同的资源类来获得两种标准的get(即获取所有内容并获得一项)?
感谢。
from flask_restful import Resource
# ...
class People(Resource):
def get(self):
return [{'name': 'John Doe'}, {'name': 'Mary Canary'}]
class Person(Resource):
def get(self, id):
return {'name': 'John Doe'}
# ...
api.add_resource(People, '/api/people')
api.add_resource(Person, '/api/people/<string:id>')
答案 0 :(得分:2)
我认为这是你正在寻找的东西:
from flask_restful import Resource
# ...
class People(Resource):
def get(self, id=None):
if not id:
return {'name': 'John Doe'}
return [{'name': 'John Doe'}, {'name': 'Mary Canary'}]
api.add_resource(People, '/api/people', '/api/people/<id>')
您可以对id
购买加上限制,将其作为参数添加到请求解析器中:
parser.add_argument('id', location='view_args', type=..)
答案 1 :(得分:0)
是的,请查看argument parsing documentation。如果需要,这将使您可以灵活地围绕与请求一起收到的参数创建一些逻辑。
from flask_restful import Api, Resource, reqparse
# ...
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('id')
class People(Resource):
def get(self):
data = parser.parse_args()
if not data['id']:
return [{'name': 'John Doe'}, {'name': 'Mary Canary'}]
else:
# data lookup using id
# for example using SQLAlchemy...
# person = Person.query.filter_by(id = data['id']).first_or_404()
return {'id': data['id'], 'name': 'John Doe'}
api.add_resource(People, '/api/people')
然后尝试: