我先贴上代码:
from twisted.application import internet, service
from twisted.internet import protocol, reactor, defer
from twisted.protocols import basic
from twisted.web import resource, server, static
import cgi
class FingerProtocol(basic.LineReceiver):
def lineReceived(self, user):
d = self.factory.getUser(user)
def onError(err):
return 'Internal error in server'
d.addErrback(onError)
def writeResponse(message):
self.transport.write(message + '\r\n')
self.transport.loseConnection()
d.addCallback(writeResponse)
class FingerResource(resource.Resource):
def __init__(self, users):
print 'FingerResource is initialized'
self.users = users
resource.Resource.__init__(self)
# we treat the path as the username
def getChild(self, username, request):
"""
'username' is a string.
'request' is a 'twisted.web.server.Request'.
"""
print self.users
messagevalue = self.users.get(username)
username = cgi.escape(username)
if messagevalue is not None:
messagevalue = cgi.escape(messagevalue)
text = '<h1>%s</h1><p>%s</p>' % (username,messagevalue)
else:
text = '<h1>%s</h1><p>No such user</p>' % username
return static.Data(text, 'text/html')
class FingerService(service.Service):
def __init__(self, filename):
self.users = {}
self.filename = filename
def _read(self):
for line in file(self.filename):
user, status = line.split(':', 1)
user = user.strip()
status = status.strip()
self.users[user] = status
self.call = reactor.callLater(30, self._read)
def startService(self):
self._read()
service.Service.startService(self)
def stopService(self):
service.Service.stopService(self)
self.call.cancel()
def getUser(self, user):
return defer.succeed(self.users.get(user, "No such user"))
def getFingerFactory(self):
f = protocol.ServerFactory()
f.protocol = FingerProtocol
f.getUser = self.getUser
return f
def getResource(self):
print 'getResource is called.'
r = FingerResource(self.users)
return r
application = service.Application('finger', uid=1, gid=1)
f = FingerService('./users')
serviceCollection = service.IServiceCollection(application)
f.setServiceParent(serviceCollection)
internet.TCPServer(79, f.getFingerFactory()
).setServiceParent(serviceCollection)
internet.TCPServer(8000, server.Site(f.getResource())
).setServiceParent(serviceCollection)
运行这段代码后,每次我更新users文件的内容以后,getResource返回的FingerResource实例里的users变量是如何被更新的?在这段代码里,我看不到它有被更新!请懂的人帮忙解释一下,谢谢!
我已经找到原因了。
users是字典类型,r = FingerResource(self.users)这里传递的是users引用;self.users[user] = status,这里会改变users的内容,所以会看到users每次都有更新。