SQLAlchemy will wrap that psycopg2 exception underneath IntegrityError (or at least DBAPIError at the bottommost) so you need to catch the SQLAlchemy-specific expression. of course you should also test it with an existing row to make sure it actually catches and works!
On Thu, Feb 4, 2021, at 8:42 PM, Vitaly Kruglikov wrote: > Thanks Mike! I followed up on your suggestion concerning savepoints and came > up with the following code snippet. Does this look right to you? > > ``` > try: > with orm_session.begin_nested(): > orm_session.add(record) > except psycopg2.errors.UniqueViolation as error: # or is it > `sqlalchemy.exc.IntegrityError`??? > # Matching metadata row already inserted by someone else > # Fetch and return existing record > > # We inserted it! > return record > ``` > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/b3002fec-c8ac-4b41-8101-1283455bfe7dn%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/b3002fec-c8ac-4b41-8101-1283455bfe7dn%40googlegroups.com?utm_medium=email&utm_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/f693c8a5-53d4-4bde-ba7d-94fe7ae875dd%40www.fastmail.com.