【问题标题】:Python3 Flask route variable shows up as the variable name instead of value passed from postmanPython3 Flask 路由变量显示为变量名而不是从邮递员传递的值
【发布时间】:2020-10-03 00:09:57
【问题描述】:

我有以下 python flask api 路由:

@user_api.route("/<int:id>", methods=["GET"])
@Authentication.auth_required
def get_user(id):
    """
    Get a user
    """
    print(f"User id: {id}")
    user = user_schema.dump(UserModel.get_user(id))
    if not user:
        print(f"User id: {id} not found!")
        return custom_response({"error": f"User {id} not found!"}, 400)
    return custom_response(user_schema.dump(user), 200)

GET 来自http://localhost:5555/api/v1/users/5 的邮递员总是以:

{
    "error": "User id not found!"
}

python 控制台输出显示:

User id: id
User id: id not found!

这意味着路由变量最终在函数中作为变量名而不是值。 intstring 变量类型都会发生这种情况。这很奇怪。我错过了什么?

【问题讨论】:

  • 如果在执行其他任何操作之前打印repr(id) 会得到什么?
  • 用户 id: id, 'id'
  • 您是否尝试将命名参数更改为xpto 看看会发生什么?证明测试了您共享的代码,它将更正值打印为路径中的整数。
  • 会不会id是你的装饰器使用的变量名?并因此在到达get_user 之前被覆盖?那么如果你临时更改名称会发生​​什么。
  • 我尝试了userid,结果相同。没用。

标签: python routes url-routing flask-restful url-parameters


【解决方案1】:

这是由于将kwargs 传递给装饰函数时@Authentication.auth_required 装饰函数中的错误。它错过了一个星号。因此,它错误地传递了*kwargs,而不是**kwargs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2019-05-08
    • 2022-12-18
    • 2023-03-27
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多