我如何使用 Python Flask 模仿 Java Springs @PathVariable

How do I mimic Java Springs @PathVariable using Python Flask

from flask import Flask, jsonify, request
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)
user_dict = {}


class User(Resource):
    def __init__(self):
        user_id = 0

    def get(self):
        return jsonify(user_dict[id])

api.add_resource(User, "/user")

if __name__ == "__main__":
    app.run(debug=True)

想法是,当向 /user/1 发出 GET 请求时,然后 user_dict 的 key/value 对的获取方法 returns。如何在 Python 中设置路径变量?请假设字典不为空。

Flask 在 URL 路径注册中使用 <variable_name> or <converter:variable_name> placeholders

Flask-Restful中显示的例子中使用了这个Quickstart documentation:

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

这里<string:todo_id>是一个路径变量,作为参数传递给TodoSimple.get()TodoSimple.put()方法。

Flask-Restful 否则假定您对 Flask 的模式有一般的了解,我强烈建议您至少通读 Flask Quickstart document, and I recommend you also work through the tutorial,如果没有其他的话。

对于您的具体示例,如果用户 ID 始终为整数,请使用:

class User(Resource):
    def get(self, user_id):
        return jsonify(user_dict[user_id])

api.add_resource(User, "/user/<int:user_id>")