zoukankan      html  css  js  c++  java
  • Django中加表锁

    一:定义model时改写objects

    from django.db import connection
    from django.db import models
    
    
    class LockingManager(models.Manager):
        """ Add lock/unlock functionality to manager.
    
        Example:
            定义model:
                class User(models.Model):
                    name = models.CharField(max_length=32)
                    objects = LockingManager()
    
            加表锁:
                User.objects.lock()
            解表锁:
                User.objects.unlock()
    
        """
    
        def lock(self):
            """ Lock table.
    
            Locks the object model table so that atomic update is possible.
            Simulatenous database access request pend until the lock is unlock()'ed.
    
            Note: If you need to lock multiple tables, you need to do lock them
            all in one SQL clause and this function is not enough. To avoid
            dead lock, all tables must be locked in the same order.
    
            See http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html
            """
    
            cursor = connection.cursor()
            table = self.model._meta.db_table
            print("Locking table %s" % table)
            cursor.execute("LOCK TABLES %s WRITE" % table)
            row = cursor.fetchone()
            return row
    
        def unlock(self):
            """ Unlock the table. """
            cursor = connection.cursor()
            table = self.model._meta.db_table
            cursor.execute("UNLOCK TABLES")
            row = cursor.fetchone()
            return row
    
    
    class User(models.Model):
        name = models.CharField(max_length=32)
        objects = LockingManager()

    二:使用表锁、释放表锁

    import os
    import django
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm_table_lock.settings")
    django.setup()
    
    from app01 import models
    
    import time
    
    # 加表锁
    models.User.objects.lock()
    time.sleep(10)
    # 释放锁
    models.User.objects.unlock()
    

      

  • 相关阅读:
    java 数组及数组得内存管理总结
    js 日期格式化
    url获取参数值,支持中文、英文
    C# log4net 的日志代码配置
    js 处理浏览器显示地址
    mui <a>标签跳转失效的处理
    js 实时输入事件
    asp.mvc 页面获取当前请求的控制器和方法
    js 获取元素值
    DllImport System.DllNotFoundException 找不到指定的模块。 (Exception from HRESULT: 0x8007007E)
  • 原文地址:https://www.cnblogs.com/maple-shaw/p/12368876.html
Copyright © 2011-2022 走看看