Flask错误或404查询导致SQL错误。

huangapple go评论40阅读模式
英文:

Flask error or 404 query resulting in SQL error

问题

尝试清理一下我的Flask代码。我有这行代码是可以工作的:

user = User.query.filter_by(username=username).first()

但我更喜欢使用这个,这样我就可以抛出一个404错误。然而,尽管上面的代码可以工作,但这个却给了我一个错误:

user = User.query.get_or_404(username=username)

TypeError: get_or_404()收到一个意外的关键字参数'username'。如果我尝试这样:

user = User.query.get_or_404(username)

我还是会得到一个错误:

> [SQL: SELECT "user".id AS user_id, "user".username AS user_username,
> "user".email AS user_email, "user".password_hash AS
> user_password_hash, "user".about_me AS user_about_me, "user".last_seen
> AS user_last_seen, "user".is_confirmed AS user_is_confirmed,
> "user".confirmed_on AS user_confirmed_on FROM "user" WHERE "user".id =
> %(pk_1)s] [parameters: {'pk_1': 'john'}]

我应该如何使用这个查询?看起来错误似乎试图将名字作为ID,而实际上应该是一个数字。

英文:

I'm trying to clean up some of my Flask code. I have this line which works:

user = User.query.filter_by(username=username).first()

But my preference is to use this so I can throw a 404. However whilst the above code works, this gives me an error:

user = User.query.get_or_404(username=username)

TypeError: get_or_404() got an unexpected keyword argument 'username'. If I try this:

user = User.query.get_or_404(username)

I also get an error:

> [SQL: SELECT "user".id AS user_id, "user".username AS user_username,
> "user".email AS user_email, "user".password_hash AS
> user_password_hash, "user".about_me AS user_about_me, "user".last_seen
> AS user_last_seen, "user".is_confirmed AS user_is_confirmed,
> "user".confirmed_on AS user_confirmed_on FROM "user" WHERE "user".id =
> %(pk_1)s] [parameters: {'pk_1': 'john'}]

How should I be using this query? It seems the error is trying to put the name as the ID which is obviously expecting a number.

答案1

得分: 2

flask-sqlalchemy中,类似于get(pk)get_or_404(param)也期望在参数中提供模型的主键。在你的情况下,你的username不是User模型的主键。

相反,你可以使用user = User.query.filter_by(username=username).first_or_404()来在用户不存在时返回404。

英文:

In flask-sqlalchemy, like get(pk), get_or_404(param) also expects the primary key of the model inside the parameter. In your case, your username is not the primary key of the User model.

Instead, you can use user = User.query.filter_by(username=username).first_or_404() to get 404 if user not exists.

huangapple
  • 本文由 发表于 2023年2月27日 16:58:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578445.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定