2012-03-30 31 views
4

我正在構建一個使用Twisted的XML-RPC服務器,它定期檢查其源文件的時間戳是否發生了變化,並使用rebuild重新加載它們。Twisted代碼重新加載的限制

from twisted.python.rebuild import rebuild 

rebuild(mymodule) 

的服務器公開得到重新加載罰款,但在另一種協議類活躍,在同一類的mymodule調用回調函數,但他們不使用的功能的重載版本的功能。這個協議只有一個dict作爲值的正常功能。

我發現這個mixin類打算處理rebuild的限制。

http://twistedmatrix.com/documents/current/api/twisted.python.rebuild.Sensitive.html

如何確保我的回調使用最新的代碼?

回答

2

你是對的;這是twisted.python.rebuild的限制。它正在更新現有實例的__class__屬性以及導入的函數和類。

一個對付這種方式是簡單地submit a patch to Twisted,對於這種情況下修復rebuild

但是,如果您想使用Sensitive達到預期目的,您還可以實現回調保持類,以在當前版本的Twisted上使用rebuild。以下示例演示如何使用相關類的所有三種方法來更新指向函數的回調字典。請注意,即使沒有if needRebuildUpdate...測試,直接調用x()將始終獲得最新的版本。

from twisted.python.rebuild import rebuild, Sensitive 
from twisted.python.filepath import FilePath 

p = FilePath("mymodule.py") 
def clearcache(): 
    bytecode = p.sibling("mymodule.pyc") 
    if bytecode.exists(): 
     bytecode.remove() 
clearcache() 
p.setContent("def x(): return 1") 
import mymodule 
from mymodule import x 
p.setContent("def x(): return 2") 

class Something(Sensitive, object): 
    def __init__(self): 
     self.stuff = {"something": x} 
    def invoke(self): 
     if self.needRebuildUpdate(): 
      for key in list(self.stuff): 
       self.stuff[key] = self.latestVersionOf(self.stuff[key]) 
      self.rebuildUpToDate() 
     return self.stuff["something"]() 

def test(): 
    print s.invoke() 
    print x() 

s = Something() 
test() 

clearcache() 
rebuild(mymodule) 

test()