如何在python 3中模拟postgresql序列nextval

如何在python 3中模拟postgresql序列nextval,python,python-3.x,singleton,python-multithreading,Python,Python 3.x,Singleton,Python Multithreading,我想知道在python 3中模拟postgresql nexval的最佳方法是什么 我想要一个变量/对象attr,它的值在请求时自动递增。db sequence nextval的工作原理也是如此。它将是“daily sequencer”,其值在每次get调用时递增(并将在午夜使用cronjob重置) 我的想法是使用Singleton(后面有一些持久缓存),但在多线程环境中它失败了 class OnlyOne: class __OnlyOne: key = "key"

我想知道在python 3中模拟postgresql nexval的最佳方法是什么

我想要一个变量/对象attr,它的值在请求时自动递增。db sequence nextval的工作原理也是如此。它将是“daily sequencer”,其值在每次get调用时递增(并将在午夜使用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)
有人有更好的主意吗


为此,Python提供了一个名为
线程化
的库

import threading
我认为最简单的解决办法就是把你的房子锁起来。您可以考虑如何更好地实现,但是您可以在
\uuuu init\uuuu
中创建一个
锁:

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

谢谢你的帮助。不幸的是,我没能保证多进程安全。对我来说,最终的解决方案是用一个工人为芹菜队列创建异步任务,所以这有点瓶颈,但速度很快,也不那么痛苦。