Python3 Flask 路由变量显示为变量名而不是从邮递员传递的值
Posted
技术标签:
【中文标题】Python3 Flask 路由变量显示为变量名而不是从邮递员传递的值【英文标题】:Python3 Flask route variable shows up as the variable name instead of value passed from postman 【发布时间】: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!
这意味着路由变量最终在函数中作为变量名而不是值。 int
和 string
变量类型都会发生这种情况。这很奇怪。我错过了什么?
【问题讨论】:
如果在执行其他任何操作之前打印repr(id)
会得到什么?
用户 id: id, 'id'
您是否尝试将命名参数更改为xpto
看看会发生什么?证明测试了您共享的代码,它将更正值打印为路径中的整数。
会不会id
是你的装饰器使用的变量名?并因此在到达get_user
之前被覆盖?那么如果你临时更改名称会发生什么。
我尝试了userid
,结果相同。没用。
【参考方案1】:
这是由于将kwargs
传递给装饰函数时@Authentication.auth_required
装饰函数中的错误。它错过了一个星号。因此,它错误地传递了*kwargs
,而不是**kwargs
。
【讨论】:
以上是关于Python3 Flask 路由变量显示为变量名而不是从邮递员传递的值的主要内容,如果未能解决你的问题,请参考以下文章
NSStringFromSelector 返回变量名而不是变量值