Is get_or_create() thread safe

后端 未结 4 1814
一向
一向 2020-12-24 11:46

I have a Django model that can only be accessed using get_or_create(session=session), where session is a foreign key to another Django model.

Since I am

4条回答
  •  自闭症患者
    2020-12-24 12:42

    I was having this problem with a view that calls get_or_create.

    I was using Gunicorn with multiple workers, so to test it I changed the number of workers to 1 and this made the problem disappeared.

    The simplest solution I found was to lock the table for access. I used this decorator to do the lock per view (for PostgreSQL):

    http://www.caktusgroup.com/blog/2009/05/26/explicit-table-locking-with-postgresql-and-django/

    EDIT: I wrapped the lock statement in that decorator in a try/except to deal with DB engines with no support for it (SQLite while unit testing in my case):

    try:
        cursor.execute('LOCK TABLE %s IN %s MODE' % (model._meta.db_table, lock))
    except DatabaseError: 
        pass
    

提交回复
热议问题