简体   繁体   English

SQLAlchemy Query返回None

[英]SQLAlchemy Query returning None

I have a web application using SQLAlchemy and MySQL-server on my ubuntu 16 & Nginx + uwsgi. 我在我的ubuntu 16和Nginx + uwsgi上有一个使用SQLAlchemy和MySQL-server的Web应用程序。

while creating the engine, i put 在创建引擎的同时,我放了

echo=True

to get tracing of the query. 获取查询的跟踪。 I have problem registering user, everytime user_loader is called on flask login, I execute: 我有注册用户的问题,每次在flask登录时调用user_loader,我执行:

dbsession.query(User).filter_by(id=user_id).first()

The result i get is : 我得到的结果是:

INFO sqlalchemy.engine.base.Engine SELECT user.id AS user_id, user.name AS user_name, user.email AS user_email, user.pass$
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]: FROM user
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]: WHERE user.id = %s
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]:  LIMIT %s
Mar 29 23:48:56 ubuntu-512mb-sgp1-01 uwsgi[26160]: 2017-03-29 23:48:56,517 INFO sqlalchemy.engine.base.Engine ('61', 1)

The result is None. 结果是无。 However, the on the above example, using user_id = 61 , , I can find the user on mysql shell in ubuntu to get user id 61. 但是,在上面的例子中,使用user_id = 61,我可以在ubuntu中的mysql shell上找到用户获取用户ID 61。

When i refresh the page a few times, then the result will come out. 当我刷新页面几次,结果就会出来。 Once user finished registering, they will be redirected to login page, upon completing the form, it shows error "Please register", which is triggered if user is now found using this query: 一旦用户完成注册,他们将被重定向到登录页面,在完成表单后,它会显示错误“请注册”,如果现在使用此查询找到用户,则会触发该错误:

dbsession.query(User).filter_by(id=user_id).first()

On registration my code is: 在注册时我的代码是:

user = User(name=name, email=email, password=password)
dbsession.add(user)
dbsession.commit()
return redirect(url_for('login'))

checking has been done to ensure name, email password is valid. 检查已完成,以确保名称,电子邮件密码有效。

Thanks 谢谢

Solved the problem. 解决了这个问题。

Thanks to @iljaEverila. 感谢@iljaEverila。

Basically I need to make sure the dbsession from SQLAlchemy has persisted the data and there is no pending transaction. 基本上我需要确保来自SQLAlchemy的dbsession已经持久保存数据并且没有待处理的事务。 So that once user registered and user_loader is invoke, i just need to call: 因此,一旦用户注册并调用user_loader,我只需要调用:

dbsession.commit()

Then calling this: 然后调用这个:

dbsession.query(User).filter_by(id=user_id).first()

will be successful. 会成功的。

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM