您将资源丰富的路由与参数解析混合在一起。
Resourceful Routing
是应用程序的端点。
以下列出了不同路线的示例:
-
localhost:5000/api/trainer/
-
localhost:5000/api/trainer/profile
-
localhost:5000/api/trainer/profile/6385d786-ff51-455e-a23f-0699c2c9c26e
-
localhost:5000/api/trainer/profile/4385d786-ef51-455e-a23f-0c99c2c9c26d
请注意,可以使用资源路由将最后两个分组。
RequestParser
是Flask-RESTPlus内置的对请求数据验证的支持。这些可以是查询字符串或POST形式的编码数据等。
使用您提供的不完整代码,可以像这样实现所需的功能
from flask import Flask
from flask_restplus import Resource,Api
app = Flask(__name__)
api = Api(app)
# List of trainers,just basic example instead of DB.
trainers = [
'6385d786-ff51-455e-a23f-0699c2c9c26e','7c6d64ae-8334-485f-b402-1bf08aee2608','c2a427d5-5294-4fad-bf10-c61018ba49e1'
]
class TrainerById(Resource):
def get(self,trainer_uuid):
# In here,trainer_uuid becomes <class 'uuid.UUID'>,so you can
# convert it to string.
if str(trainer_uuid) in trainers:
return {'msg': f"Trainer with UUID {trainer_uuid} exists"},200
else:
return {'msg': f"Trainer with uuid {trainer_uuid} not found"},404
# This means after profile/,next expected keyword is UUID with name in route
# as trainer_uuid.
api.add_resource(TrainerById,'/api/trainer/profile/<uuid:trainer_uuid>')
if __name__ == '__main__':
app.run(debug=True)
本文链接:https://www.f2er.com/3150023.html