PUT request not working, Flask-RESTful, SQLAlchemy
I believe the problem is with the changes being made to the database (from third to last line:) db.session.commit()
. For example, take a user: username = "Foo", email = " Bar@yahoo.com ". If I put {"email": " changed@gmail.com "} in the body of the PUT request , printing out "user.email" after the assignment, you will see that the value has indeed changed. Subsequently, however, when the database is queried, the email remains unchanged. Anyway, I'm really having a hard time figuring out what I'm missing, so any help is appreciated!
class UserAPI(Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('username', type=str, location='json')
self.parser.add_argument('email', type=str, location='json')
self.parser.add_argument('password', type=str, location='json')
super(UserAPI, self).__init__()
def put(self, id):
# Not working
user = User.query.filter_by(id=id).first()
if user is not None:
args = self.parser.parse_args()
for key, value in args.items():
if args[key] is not None:
user.key = value
db.session.commit()
return {"user": marshal(user,user_field) }
return {"error": "User not found"}, 404
source to share
Change user.key = value
to setattr(user, key, value)
.
Instead of setting the attribute you want here ( user.email
), you set user.key
. Since user.key
it is probably not a field in a database column (and certainly not the one you intend to set), the changes are not converted to the database when called db.session.commit()
.
source to share