gpt4 book ai didi

python - Flask Restful无法映射到pathparam资源

转载 作者:太空宇宙 更新时间:2023-11-03 20:10:42 24 4
gpt4 key购买 nike

我有一个像这样的 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

最佳答案

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

资源路由是应用程序的端点。

下面列出了不同路线的示例:

  • 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 是 Fl​​ask-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)

关于python - Flask Restful无法映射到pathparam资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58735735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com