Error when working with flask sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed

Question:

I am very new with this and I’m just trying out flask and I can’t seem to be able to get around this issue with sqlalchemy

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint 
failed: Login Info.username [SQL: 'INSERT INTO "Login Info" (username, 
password) VALUES (?, ?)'] [parameters: ('audyappy', 'secret')] (Background on 
this error at: http://sqlalche.me/e/gkpj)

from project.py:

@app.route('/register', methods=['GET',"POST"])
def register():
    if request.method == "POST":
        newUser = Login_Info(username=request.form['username'], password=request.form['password'])
        session.add(newUser)
        flash('You have registered successfully')
        session.commit()
        return redirect(url_for('login'))
    else:
        return render_template('register.html')

This is from database_setup.py:

class Login_Info(Base):
    __tablename__ = 'Login Info'
    id = Column(Integer, primary_key=True)
    username = Column(String, nullable=False, unique=True)
    password = Column(String, nullable=False)

Full traceback:

Traceback (most recent call last): File
“C:UsersaudriAppDataRoamingPythonPython37site-packagesflaskapp.py”,
line 2309, in call
return self.wsgi_app(environ, start_response) File “C:UsersaudriAppDataRoamingPythonPython37site-packagesflaskapp.py”,
line 2295, in wsgi_app
response = self.handle_exception(e) File “C:UsersaudriAppDataRoamingPythonPython37site-packagesflaskapp.py”,
line 1741, in handle_exception
reraise(exc_type, exc_value, tb) File “C:UsersaudriAppDataRoamingPythonPython37site-packagesflask_compat.py”,
line 35, in reraise
raise value File “C:UsersaudriAppDataRoamingPythonPython37site-packagesflaskapp.py”,
line 2292, in wsgi_app
response = self.full_dispatch_request() File “C:UsersaudriAppDataRoamingPythonPython37site-packagesflaskapp.py”,
line 1815, in full_dispatch_request
rv = self.handle_user_exception(e) File “C:UsersaudriAppDataRoamingPythonPython37site-packagesflaskapp.py”,
line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb) File “C:UsersaudriAppDataRoamingPythonPython37site-packagesflask_compat.py”,
line 35, in reraise
raise value File “C:UsersaudriAppDataRoamingPythonPython37site-packagesflaskapp.py”,
line 1813, in full_dispatch_request
rv = self.dispatch_request() File “C:UsersaudriAppDataRoamingPythonPython37site-packagesflaskapp.py”,
line 1799, in dispatch_request
return self.view_functionsrule.endpoint File “D:AudricWorkfirstcodepythonFCASISAC403(FLASK-SHARED)deploy
-experimentalproject.py”, line 80, in register
session.commit() File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormscoping.py”,
line 153, in do
return getattr(self.registry(), name)(*args, **kwargs) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormsession.py”,
line 943, in commit
self.transaction.commit() File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormsession.py”,
line 467, in commit
self._prepare_impl() File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormsession.py”,
line 447, in _prepare_impl
self.session.flush() File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormsession.py”,
line 2254, in flush
self._flush(objects) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormsession.py”,
line 2380, in _flush
transaction.rollback(_capture_exception=True) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyutillanghelpers.py”,
line 66, in exit
compat.reraise(exc_type, exc_value, exc_tb) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyutilcompat.py”,
line 249, in reraise
raise value File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormsession.py”,
line 2344, in _flush
flush_context.execute() File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormunitofwork.py”,
line 391, in execute
rec.execute(self) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormunitofwork.py”,
line 556, in execute
uow File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormpersistence.py”,
line 181, in save_obj
mapper, table, insert) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyormpersistence.py”,
line 866, in _emit_insert_statements
execute(statement, params) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyenginebase.py”,
line 948, in execute
return meth(self, multiparams, params) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemysqlelements.py”,
line 269, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params) File
“C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyenginebase.py”,
line 1060, in _execute_clauseelement
compiled_sql, distilled_params File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyenginebase.py”,
line 1200, in _execute_context
context) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyenginebase.py”,
line 1413, in _handle_dbapi_exception
exc_info File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyutilcompat.py”,
line 265, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyutilcompat.py”,
line 248, in reraise
raise value.with_traceback(tb) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyenginebase.py”,
line 1193, in _execute_context
context) File “C:UsersaudriAppDataRoamingPythonPython37site-packagessqlalchemyenginedefault.py”,
line 509, in do_execute
cursor.execute(statement, parameters) sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE
constraint failed: Login Info.username [SQL: ‘INSERT INTO “Login Info”
(username, password) VALUES (?, ?)’] [parameters: (‘audyappy’,
‘secret’)] (Background on this error at: http://sqlalche.me/e/gkpj)

I can’t seem to find the issue so it would be great if you would help me. Thanks!

Asked By: Pencilcase

||

Answers:

You have a unicity constraint on the username column of the table where you are trying to insert data: username = Column(String, nullable=False, unique=True)

The username value you are trying to insert is already there in that table. Try deleting the problematic record and rerun your insert or run your insert with a different value.

Answered By: Alexis.Rolland

Looking at your output this seems to be what caused the problem.

“D:AudricWorkfirstcodepythonFCASISAC403(FLASK-SHARED)deploy -experimentalproject.py”, line 80, in register session.commit() File

The session.commit() is probably not able to commit data to the database. I think you have not setup your database properly. Since you are using Flask I would suggest using Flask-SQLAlchemy which makes using SQLAlchemy on flask apps much easier.

Check out this great tutorial on this topic. https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database .

Hope this helps.

Answered By: ikuamike

Maybe you re-commit the same data to database.
And as for primary key is unique, so there get an error.
Try this:

try:
    session.commit()
except Exception as e:
    print(e)

to replace your codeļ¼š

session.commit()
Answered By: Perter Liu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.