Flask Restful无法映射到pathparam资源

时间:2019-11-06 17:39:16

标签: python rest api flask flask-restful

我有一个烧瓶宁静的资源,像这样:

api.add_resource(TrainerById, '/api/trainer/<int:uuid>')

具有这样的源代码:

class TrainerById(Resource):
    def get(self):
        data = trainer_by_id_parser.parse_args()
        trainer_uuid = data['uuid']
        new_trainer = Trainer.find_by_uuid(trainer_uuid)
        if not new_trainer:
            return {'msg': f"Trainer with uuid {trainer_uuid} not found"}, 401
        else:
            return {'msg': to_json_trainer(new_trainer)}

我想从路径参数返回带有UUID的培训师的trainer个人资料,但是问题是,每当我尝试访问端点时,它都会返回404:

localhost:5000/api/trainer/profile/886313e1-3b8a-5372-9b90-0c9aee199e5d #gives 404

1 个答案:

答案 0 :(得分:0)

您将资源丰富的路由与参数解析混合在一起。

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)