2012-03-30 63 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()