使用Twisted Python的SMTP模块清理资源 [英] Cleanup of resources with the SMTP module of Twisted Python

查看:10
本文介绍了使用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,它可以通过对循环中的对象集合施加任意顺序来收集此类对象。)

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

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

这篇关于使用Twisted Python的SMTP模块清理资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆