使用Twisted Python的SMTP模块清理资源

本教程将介绍使用Twisted Python的SMTP模块清理资源的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

使用Twisted Python的SMTP模块清理资源 教程 第1张

问题描述

这与前面回答的问题有关: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,它可以通过对循环中的对象集合施加任意顺序来收集此类对象。)

接下来,考虑在消息传递工厂中打开数据库连接(或启动连接池),并在所有消息传递对象之间共享它。这样,您不需要清除的连接,因为请问在以后的消息中重复使用它们,并且您不会为每条消息分配新的连接,因此不会发生泄漏。

最后,如果您确实需要任何针对每个事务的对象,您可以在eomReceivedconnectionLost对象上的eomReceived实现中清除它们。一旦SMTP事务的数据部分完成(因为接收到所有数据或因为连接丢失),将调用其中一个方法。请注意,由于SMTP支持在单个事务中将一封邮件传递给多个收件人,因此可能有多个IMessage对象参与,即使只有一个IMessageDelivery对象也是如此。因此,您可能希望将消息传递对象上成功的validateTo调用的调用数与消息对象上的eomReceived/connectionLost调用数进行反匹配。当每次调用的次数相同时,交易即告完成。

好了关于使用Twisted Python的SMTP模块清理资源的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。