我想知道在python 3中模拟postgresql nexval的最佳方法是什么。
我想要变量/ object attr,其值在请求其值时自动增加。 db sequence nextval的工作原理与此相同。它将是“每日音序器”,其值在每次接听电话时递增(并且将使用cronjob在午夜重置)。
我的想法是使用Singleton(后面有一些持久缓存),但在多线程环境中失败。
class OnlyOne:
class __OnlyOne:
key = "key"
def __init__(self):
val = cache.get(self.key, None)
if val is None:
val = 0
cache.set(self.key, val)
self.val = val
def __str__(self):
return str(self.nextval)
@property
def nextval(self):
self.val += 1
cache.set(self.key, self.val)
return self.val
instance = None
def __init__(self):
if not OnlyOne.instance:
OnlyOne.instance = OnlyOne.__OnlyOne()
def __getattr__(self, name):
return getattr(self.instance, name)
有人有更好的主意吗?
由于
答案 0 :(得分:0)
Python有一个名为threading
的库。
import threading
我认为最简单的解决方案就是锁定你的财产。您可以考虑如何更好地实施,但您可以在Lock
中创建__init__
:
self.lock = threading.Lock()
然后使用锁定包装对属性的访问:
self.lock.acquire() # grab the lock
# Code in here is single threaded
self.val += 1
retval = self.val
cache.set(self.key, self.val)
self.lock.release() # release the lock
return retval # Returning this to avoid a race with self.val