I’m using a get_or_create pattern similar to the answer to this question:
Does SQLAlchemy have an equivalent of Django's get_or_create?
But I’m having trouble with another thread creating an instance (with the same pk) between the ‘select’ and the ‘insert’ of the first thread.
Should the get_or_create function lock the table for the two queries?
What is the best way of implementing locking with SqlAlchemy?
I’m using postgresql: http://www.postgresql.org/docs/current/static/sql-lock.html
The only sqlalchemy locking functionality I can see is ‘for update‘, which doesn’t seem to be the right type of locking?
It seems I have misunderstood your reply to my answer in the other question.
What you are looking for here probably isn’t locking directly, but transactions.
http://www.sqlalchemy.org/docs/core/connections.html#using-transactions
But… are you trying to prevent executing the same insert twice? In that case you would need a lock somewhere in python (or catch the duplicate key error). That is actually the only foolproof way to do it. Try to insert and get it if you get a duplicate key error.