MongoEngine:关闭连接

MongoEngine: Close connection

我花了很长时间试图找到一个使用 MongoEngine 并关闭连接的简单示例。终于想通了并发布我的代码。

我以为 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()

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

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')

您也可以省略别名,因为在连接和断开连接时它将默认为 'default'。

它可以通过连接 class 进行管理,如下所示。它使用 __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 

根据 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' 后断开连接,一切正常