Ashish Mysterio
Ashish Mysterio

Reputation: 197

flask_sqlalchemy UPDATE row details not updating mySQL database

I have a flask app and a mySQL database connected to it. I am using POSTMAN to send GET/POST requests to the flask endpoints for user add, update and delete. I am able to successfully add users to the database but while I am updating the flask app does not throw any errors where as the postman also displays a successful JSON response that "User updated!!!" But when I perform SELECT * FROM Users operation in my SQL Workbench the details are not being updated.

My implementation is as follows - I have created a model User with two columns username and password.

The user update API looks like -

from flask_restful import Resource
from flask_sqlalchemy import SQLAlchemy
from model import User


class Update_User(Resource):
    def post(self):
        data = request.get_json(force=True)
        usr = User.query.filter_by(username=data['username']).first()
        print(1, usr.username, usr.password)
        
        usr.password = data['new_password']
        print(2, usr.username, usr.password)

        db.session.commit()
        db.session.close()

        return {"res": "User updated!!!!"}

flask output:

1 Ash 12345
2 Ash 00000

Just for better understanding, what is better to use ? Python SQLAlchemy or flask's own SQLAlchemy ? Because there are other instances as well where I am facing trouble like while updating two rows simultaneously using add_all()

Upvotes: 1

Views: 6719

Answers (2)

Ashish Mysterio
Ashish Mysterio

Reputation: 197

After struggling I found out where I was wrong, someone else facing the issue can try the following thing.

What worked for me -

usr.password = data['new_password']
db.session.merge(usr)
db.session.commit()

Things that did not work for me despite having them as answer on some of the stackoverflow questions -

usr.data["password"] = data['new_password']
db.session.commit()
--------------------------------------------
usr.password = data['new_password']
db.session.add(usr)
db.session.commit()
--------------------------------------------
usr.data = { "password": data['new_password'] }
db.session.commit()

Hope this might help you!

Upvotes: 3

kielni
kielni

Reputation: 5009

You need to add the object to the session to tell SQLAlchemy that you want to you've made changes (after updating it, before committing):

usr.password = data['new_password']
db.session.add(usr)
db.session.commit()

See more details in the SQLAlchemy docs: https://docs.sqlalchemy.org/en/13/orm/tutorial.html#adding-and-updating-objects

Upvotes: 1

Related Questions