lock tables decorator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def require_lock(*tables):
    def _lock(func):
        def _do_lock(*args,**kws):
            #lock tables
            cursor = connection.cursor()
            cursor.execute("LOCK TABLES %s WRITE" %' '.join(tables))
            try:
                result = func(*args,**kws)
            except Exception,e:
                raise Exception(e)
            else:
                return result
            finally:
                #unlock tables
                cursor.execute("UNLOCK TABLES")
                if cursor:cursor.close()

        return _do_lock
    return _lock

'''
    example:

    @require_lock(table_A,table_B)
    fuc(args):
        pass
'''

More like this

  1. Locking tables by miohtama 5 years, 9 months ago
  2. Django Row Level Locking (Prevents race conditions if used correctly) by sleepycal 3 years, 11 months ago
  3. Really simple locking by sirex 3 years, 2 months ago
  4. Model Locking Mixin & Decorator (MySQL Advisory Locks) by pio 2 years, 11 months ago
  5. Prefetch id for Postgresql backend by bretth 2 years ago

Comments

svetlyak (on September 4, 2008):

I think, that it would be better and shoter, to use try…finally block, like that:

        try:
            return func(*args,**kws)
        finally:
            #unlock tables
            cursor.execute("UNLOCK TABLES")
            cursor.close()

#

(Forgotten your password?)