mysql error while updating table using flask python [closed]

hrysbysz  于 2022-12-22  发布在  Mysql
关注(0)|答案(1)|浏览(132)

Closed. This question needs debugging details . It is not currently accepting answers.

Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem . This will help others answer the question.
Closed 3 hours ago.
Improve this question
I have been having problems while updating table using @app.route('/update-user').The table is being updated but while using the GET request using Postman it is always returning the exception {'error':'Error Inserting'}. Postman screenshot

from flask import Flask,jsonify
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:password@localhost:3306/demo'
app.config['QLALCHEMY_TRACK_MODIFICATIONS']=False
db=SQLAlchemy(app)
app.app_context().push()

class UserInfo(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    username=db.Column(db.String(100), unique=True)
    password=db.Column(db.String(100))
    def __init__(self,username,password):
        self.username=username
        self.password=password

db.create_all()
db.session.commit()
        
@app.route('/hello')
def show_hello():
    return jsonify({'message':'Hello Folks'})
@app.route('/create-users')
def create_users():
    try:
        user1=UserInfo('harsh','12345')
        user2=UserInfo('vadodara','355578')
        db.session.add(user1)
        db.session.add(user2)
        db.session.commit()
        return jsonify({'message':'Users successfully created'})
    except Exception as e:
        return jsonify({'error':'Error inserting users'})
@app.route('/update-user')
def update_user():
    try:
        user=UserInfo.query.filter_by(username='harsh').first()
        user.password='13487656'
        db.session.commit()
        return jsonify({'message:Successfully updated'})
    except Exception as e:
        return jsonify({'error':'Error inserting'})
    
if __name__=="__main__":
    app.run(debug=True)

I have dropped the table using mysql-workbench and run the code many times but the result is the same. I am not getting {'message':'successfully inserted'} as the desired output.

dy1byipe

dy1byipe1#

The reason of error is that you passing wrong type data in jsonify. here you are passing data type of set in jsonify you are passing this = {'message:successfully updated'} which is set data type. which is not json serializable.
instead of this

return jsonify({'message:Successfully updated'})

Try this:

return jsonify({'message':'Successfully updated'})

you are using try except wrong way you have hardcoded the exception with static value of 'error':'error inserting
instead of that try this

except Exception as e:
        print(e)
        return jsonify({'error':str(e)})

so this way you will get the exact error in response and console also

相关问题