MongoEngine:关闭连接

时间:2017-05-09 09:28:16

标签: python connection mongoengine disconnect

我花了很多年时间试图找到一个简单的例子,其中使用了MongoEngine并且正在关闭连接。终于找到了并发布了我的代码。

4 个答案:

答案 0 :(得分:6)

我认为最初应该使用disconnect(),但它已被删除为close()的同义词。

from mongoengine import connect

def main():

    #connect to db
    db_client = connect('my_db', host='localhost', port=27017)

    #close the connection
    db_client.close()

if __name__ == "__main__":
    main()

答案 1 :(得分:3)

我知道这是一个老问题,但是如果有人在搜索,我想我会给出一个替代答案。

close()实际上并未从MongoEngine的连接列表中删除该连接。稍后尝试连接到其他数据库时,这会导致问题。

为解决这个问题,我使用了mongoengine.connection.disconnect(即使__all__中未列出)。我的代码如下:

from mongoengine import connect
from mongoengine.connection import disconnect

db = connect(alias='some_alias')

{do stuff}

disconnect(alias='some_alias')

您也可以不使用别名,因为在连接和断开连接时,别名均默认为“默认”。

答案 2 :(得分:0)

它可以通过如下的Connection类进行管理。它使用 __ enter __ 创建连接,并使用 __ exit __ 方法将其关闭。

from mongoengine import connect
from app.config import config


class Connection:
    def __enter__(self):
        self.conn = connect(host=config.mongo_url)
        return self.conn

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.close()

然后,您可以将其与“ with” 语句一起使用。

from app.connection import Connection

with Connection():
     # do some stuff with db, connection will be closed after with statement
     pass 

答案 3 :(得分:0)

根据 mongoengine 文档

Calling disconnect() without argument will disconnect the “default” connection

正如已接受的答案所指出的,在某些情况下,在使用连接和断开连接时定义“别名”很重要。

没有定义“别名”的实验

在我的情况下,使用 alias='testdb' 连接并断开连接而不定义 'alias' 效果很好,直到我将数据库和后端移动到 docker 中。出于某种原因,在 docker 中使用 mongomock 运行测试时,我收到以下错误:

mongoengine.connection.ConnectionFailure: A different connection with alias `testdb` was already registered. Use disconnect() first

mongoengine.connection.ConnectionFailure: You have not defined a default connection

解决方案

在断开连接时也定义了 alias='testdb' 后,一切正常