使用Twisted Python的SMTP模块清理资源
问题描述
这与前面回答的问题有关: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"
解决方案
首先,永远不要使用__del__
,特别是当您有一些资源需要清理时。__del__
防止在引用周期中对对象进行垃圾回收。(或者,切换到PyPy,它可以通过对循环中的对象集合施加任意顺序来收集此类对象。)
eomReceived
或connectionLost
对象上的eomReceived
实现中清除它们。一旦SMTP事务的数据部分完成(因为接收到所有数据或因为连接丢失),将调用其中一个方法。请注意,由于SMTP支持在单个事务中将一封邮件传递给多个收件人,因此可能有多个IMessage
对象参与,即使只有一个IMessageDelivery
对象也是如此。因此,您可能希望将消息传递对象上成功的validateTo
调用的调用数与消息对象上的eomReceived
/connectionLost
调用数进行反匹配。当每次调用的次数相同时,交易即告完成。
相关文章