pythonmysqlerror-handlingflask-sqlalchemy

sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry '' " for key ""


I am developing an application with flask, mysql, and sqlalchemy. The moment I try to insert a duplicate data in a UNIQUE column the app crashes. Is there any way to catch this exception in a try except like this?

        if form.validate_on_submit():
            hashed_password = generate_password_hash(form.password.data, method='sha256')

            # write data on DB
            try:
                new_user = User(name=form.name.data, surname=form.surname.data, email=form.email.data,
                                pwd_hash=hashed_password, is_active=False, urole=form.urole.data)
                db.session.add(new_user)
                db.session.commit()

                return '<h1>Welcome, You are a new user!</h1>'
            except IntegrityError:
                return '<h1>This email alredy exists!</h1>'

Solution

  • This is how I've solved it in my app:

    import pymysql
    from sqlalchemy import exc
    
    def add_bulk_data(data):
        for entry in data:
            session.add(org)
            try:
                session.commit()
            except pymysql.err.IntegrityError as e:
                session.rollback()
            except exc.IntegrityError as e:
                session.rollback()
            except Exception as e:
                session.rollback()
    
    

    I had to encapsulate the commit() command in my try statement.