Cleanup of resources with the SMTP module of Twisted Python

不羁岁月 提交于 2019-12-06 11:12:23

First, don't ever use __del__, particularly if you have some resources you want to clean up. __del__ prevents the garbage collection of objects in reference cycles. (Alternatively, switch to PyPy which can collect such objects by imposing an arbitrary ordering on the collection of objects in the cycle.)

Next, consider opening your database connection (or start a connection pool) in the message delivery factory and sharing it between all of the message delivery objects. This way you don't need to clean the connections of, because you'll re-use them for future messages, and you aren't allocating a new one for each message, so there's no leak.

Finally, if you really need any per-transaction objects, you can clean them up in your eomReceived or connectionLost implementations on the IMessage object. One of these methods will be called once the DATA portion of the SMTP transaction is complete (either because all data was received or because the connection was lost). Note that because SMTP supports delivery of a message to multiple recipients in a single transaction, there may be more than one IMessage object participating, even though there is only a single IMessageDelivery object. So you may want to keep a counter - match up the number of calls to successful validateTo calls on the message delivery object with the number of eomReceived/connectionLost calls on the message objects. When the same number of calls of each have happened, the transaction is done.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!