Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot catch SQLAlchemy IntegrityError

Try as I might, I can't seem to catch the sqlalchemy IntegrityError correctly:

from sqlalchemy import exc  try:     insert_record() except exc.IntegrityError, exc:     print exc # this is never called     handle_elegantly() # this is never called 

As what one might expect:

IntegrityError: (IntegrityError) insert or update on table "my_table"                  violates foreign key constraint "my_table_some_column_fkey" 

I've tried to explicitly:

from sqlalchemy.exc import IntegrityError 

UPDATE:

I found something that seems to fit what's happening here, where Integrity Error isn't thrown until the session is flushed to the db, and after the try/exceptblocks have been executed: Trying to catch integrity error with SQLAlchemy

However, adding session.flush() in the try block yields an InvalidRequestError:

ERROR:root:This Session's transaction has been rolled back due to a previous             exception during flush. To begin a new transaction with this Session,             first issue Session.rollback().             Original exception was: (IntegrityError) 
like image 654
Chrispy Avatar asked Jul 02 '14 03:07

Chrispy


1 Answers

I have the same need in my Flask application, I handle it like below and it works:

from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy import exc  db = SQLAlchemy(Flask(__name__))  try:      db.session.add(resource)      return db.session.commit() except exc.IntegrityError:      db.session.rollback() 
like image 83
JsonBruce Avatar answered Oct 24 '22 11:10

JsonBruce