【发布时间】:2012-08-31 19:46:14
【问题描述】:
这与此处先前回答的问题有关:Logging SMTP connections with Twisted。我有一个在每个 ConsoleMessageDelivery 实例中创建的数据库资源,我需要确保在关闭套接字时清理它。我有一个名为 DenyFactory 的 WrappingFactory ,并且在关闭套接字时调用了 DenyFactory.unregisterProtocol 方法,但是我无法(我可以弄清楚)如何访问在被销毁的 ConsoleMessageDelivery 实例中创建的资源。我在 ConsoleMessageDelivery 中尝试了 del() 方法,但从未调用过。在这种情况下清理资源的最佳方法是什么?
class ConsoleMessageDelivery:
implements(smtp.IMessageDelivery)
def receivedHeader(self, helo, origin, recipients):
myHostname, clientIP = helo
headerValue = "by %s from %s with ESMTP ; %s" % (myHostname, clientIP, smtp.rfc822date())
# email.Header.Header used for automatic wrapping of long lines
return "Received: %s" % Header(headerValue)
def validateFrom(self, helo, origin):
# All addresses are accepted
return origin
def validateTo(self, user):
if user.dest.local == "console":
return lambda: ConsoleMessage()
raise smtp.SMTPBadRcpt(user)
class ConsoleMessage:
implements(smtp.IMessage)
def __init__(self):
self.lines = []
def lineReceived(self, line):
self.lines.append(line)
def eomReceived(self):
return defer.succeed(None)
def connectionLost(self):
# There was an error, throw away the stored lines
self.lines = None
class ConsoleSMTPFactory(smtp.SMTPFactory):
protocol = smtp.ESMTP
def __init__(self, *a, **kw):
smtp.SMTPFactory.__init__(self, *a, **kw)
self.delivery = ConsoleMessageDelivery()
def buildProtocol(self, addr):
p = smtp.SMTPFactory.buildProtocol(self, addr)
p.delivery = self.delivery
return p
class DenyFactory(WrappingFactory):
def buildProtocol(self, clientAddress):
if clientAddress.host == '1.3.3.7':
# Reject it
return None
# Accept everything else
return WrappingFactory.buildProtocol(self, clientAddress)
def unregisterProtocol(self, p):
print "Unregister called"
【问题讨论】:
-
您要删除的资源是什么?是在 lambda 中创建的 ConsoleMessage() 吗?你怎么确定它没有被垃圾收集?如果没有调用 ConsoleMessageDelivery 上的 del 方法,这可能表明真正的问题是该对象永远不会被垃圾收集,因为有东西在持有该对象。
-
我在 ConsoleMessageDelivery 的构造函数中实例化了一个对象,除此之外,它还打开了与数据库的连接。当 SMTP 连接关闭时,我需要确保数据库连接也关闭,以避免资源匮乏。有趣的是,如果我不使用任何包装工厂(如上面的 DenyFactory,也包括 TimeoutFactory),则 __del__() 方法会按预期调用。这可能是包装工厂的泄漏吗?