python - 使用 `with` 语句关闭连接

标签 python imap with-statement imaplib

我想要一个表示 IMAP 连接的类,并将其与 with 语句一起使用,如下所示:

class IMAPConnection:
    def __enter__(self):
        connection = imaplib.IMAP4_SSL(IMAP_HOST)

        try:
            connection.login(MAIL_USERNAME, MAIL_PASS)
        except imaplib.IMAP4.error:
            log.error('Failed to log in')

        return connection

    def __exit__(self, type, value, traceback):
        self.close()

with IMAPConnection() as c:
    rv, data = c.list()
    print(rv, data)

自然会失败,因为 IMAPConnections 没有属性 close。当 with 语句完成时,如何存储连接并将其传递给 __exit__ 函数?

最佳答案

您需要将连接存储在对象属性中。像这样的事情:

class IMAPConnection:
    def __enter__(self):
        self.connection = imaplib.IMAP4_SSL(IMAP_HOST)

        try:
            self.connection.login(MAIL_USERNAME, MAIL_PASS)
        except imaplib.IMAP4.error:
            log.error('Failed to log in')

        return self.connection

    def __exit__(self, type, value, traceback):
        self.connection.close()

您还想为您的类实现 list 方法。

编辑:我现在才意识到您的实际问题是什么。当您执行 with SomeClass(*args, **kwargs) as c 时, c 不是 __enter__ 方法返回的值。 cSomeClass 的实例。这是问题的根源,您从 __enter__ 返回连接并假设 c 是所述连接。

关于python - 使用 `with` 语句关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39639594/

相关文章:

邮件 : Setting custom flags on imap mail and searching for mails with custom flags

Python "with"语句堆积

python - debug_toolbar 报告的重复查询

c# - 在生产服务器上使用 SSL 身份验证在 IMAP 上获取链状态 "RevocationStatusUnknown"

使用类(wx.Python)时出现Python TypeError

PHPBREW安装imap支持错误

python - 中断或退出 "with"语句?

带有语句 : storing context 的 Python

python - 为什么(0-6)是-6 = False?

python - 使用python的字符串插值