2017-01-27 66 views
0

我想知道什麼是模擬在Python的PostgreSQL nexval的最佳方式3.如何模擬PostgreSQL的序列在Python NEXTVAL 3

我想有變量/對象ATTR,其值是自動增量上要求其價值。 db序列nextval是如何工作的。這將是「每日序」,其價值增量上分別獲得通話(和會重置午夜使用的cronjob)。

我的想法是用辛格爾頓(在後面一些持久高速緩存),但它在多線程環境中失敗。

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

Python有一個名爲threading該庫。

import threading 

我認爲最簡單的解決方案就是鎖定你的財產。你能想到的是如何更好地實現,但你可以創建一個在您__init__一個Lock

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 
+0

感謝您的幫助。不幸的是,我無法讓多進程安全。我最終的解決方案是創建異步任務芹菜隊列與一個工人,所以它有點瓶頸,但它的快速和不那麼痛苦。 – Pavel