SqlAlchemy: locking a table using the `get or create` template

I am using the get_or_create pattern similar to the answer to this question:

Does SQLAlchemy have the equivalent of get_or_create Django?

But I am having problems with another thread creating an instance (with the same pk) between "select" and "insert" of the first thread.

Should the get_or_create function lock the table for two queries? What is the best way to implement locking using SqlAlchemy?

I am using postgresql: http://www.postgresql.org/docs/current/static/sql-lock.html

The only sqlalchemy lock function that I see is " for an update , which doesn't seem to be the correct type of lock?"

+3
source share
2
+2

WoLpH , (EdgeInfo - ):

from sqlalchemy import exc

session.begin_nested()
e_info = EdgeInfo(pk_attr_1=pk_attr_1, pk_attr_2=pk_attr_2)
try:
    session.commit()
except exc.IntegrityError:
    session.rollback()
    e_info = EdgeInfo.get((pk_attr_1, pk_attr_2))
0

All Articles