簡體   English   中英

如何關閉 mongodb python 連接?

[英]How to close a mongodb python connection?

我正在做一個將一些數據寫入 mongodb 的 python 腳本。 完成后,我需要關閉連接並釋放一些資源。

這是如何在 Python 中完成的?

MongoClient實例上使用close()方法:

client = pymongo.MongoClient()

# some code here

client.close()

清理客戶端資源並斷開與 MongoDB 的連接。

通過發送一個或多個 endSessions 命令結束此客戶端創建的所有服務器會話。

關閉連接池中的所有套接字並停止監控線程。

關閉 pymongo 連接的最安全方法是將其與“with”一起使用:

with pymongo.MongoClient(db_config['HOST']) as client:
    db = client[ db_config['NAME']]
    item = db["document"].find_one({'id':1})
    print(item)

添加到@alexce 的答案中,這並不總是正確的。 如果您的連接已加密,MongoClient 將不會重新連接:

    def close(self):
        ...
        if self._encrypter:
            # TODO: PYTHON-1921 Encrypted MongoClients cannot be re-opened.
            self._encrypter.close()

另外,從 4.0 版開始,在調用close()之后,客戶端無論如何都不會重新連接。

   def close(self) -> None:
        """Cleanup client resources and disconnect from MongoDB.
        End all server sessions created by this client by sending one or more
        endSessions commands.
        Close all sockets in the connection pools and stop the monitor threads.
        .. versionchanged:: 4.0
           Once closed, the client cannot be used again and any attempt will
           raise :exc:`~pymongo.errors.InvalidOperation`.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM