简体   繁体   中英

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

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:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 2309, in call return self.wsgi_app(environ, start_response) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask_compat.py", line 35, in reraise raise value File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1718, in handle_user_exceptio n reraise(exc_type, exc_value, tb) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask_compat.py", line 35, in reraise raise value File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functionsrule.endpoint File "D:\Audric\Work\firstcode\python\FCASIS\AC403(FLASK-SHARED)\deploy -experimental\project.py", line 80, in register session.commit() File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\scoping.py", line 153, in do return getattr(self.registry(), name)(*args, **kwargs) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\session.py", line 943, in commit self.transaction.commit() File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\session.py", line 467, in commit self._prepare_impl() File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\session.py", line 447, in _prepare_impl self.session.flush() File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\session.py", line 2254, in flush self._flush(objects) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\session.py", line 2380, in _flush transaction.rollback(_capture_exception=True) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\util\langhelpers.py", line 66, in exit compat.reraise(exc_type, exc_value, exc_tb) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\util\compat.py", line 249, in reraise raise value File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\session.py", line 2344, in _flush flush_context.execute() File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\unitofwork.py", line 391, in execute rec.execute(self) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\unitofwork.py", line 556, in execute uow File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\persistence.py", line 181, in save_obj mapper, table, insert) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\orm\persistence.py", line 866, in _emit_insert_statements execute(statement, params) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\engine\base.py", line 948, in execute return meth(self, multiparams, params) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\sql\elements.py", line 269, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\engine\base.py", line 1060, in _execute_clauseelement compiled_sql, distilled_params File "C:\User s\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\engine\base.py", line 1200, in _execute_context context) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\engine\base.py", line 1413, in _handle_dbapi_exception exc_info File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\util\compat.py", line 265, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\util\compat.py", line 248, in reraise raise value.with_traceback(tb) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\engine\base.py", line 1193, in _execute_context context) File "C:\Users\audri\AppData\Roaming\Python\Python37\site-packages\sqlalchemy\engine\default.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!

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.

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

"D:\\Audric\\Work\\firstcode\\python\\FCASIS\\AC403(FLASK-SHARED)\\deploy -experimental\\project.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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM