Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy Query returning None

I have a web application using SQLAlchemy and MySQL-server on my ubuntu 16 & Nginx + uwsgi.

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:

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.

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

like image 519
Andree Wijaya Avatar asked Mar 29 '17 23:03

Andree Wijaya


1 Answers

Solved the problem.

Thanks to @iljaEverila.

Basically I need to make sure the dbsession from SQLAlchemy has persisted the data and there is no pending transaction. So that once user registered and user_loader is invoke, i just need to call:

dbsession.commit()

Then calling this:

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

will be successful.

Thanks

like image 187
Andree Wijaya Avatar answered Oct 04 '22 11:10

Andree Wijaya