MongoEngine:关闭连接

11

我花了很长时间试图寻找一个MongoEngine被使用并且连接被关闭的简单例子。最终弄明白了,并发布我的代码。

4个回答

15

我知道这是一个老问题,但如果还有人在搜索,我想提供另一种答案。

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

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


8

我曾认为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
这里是MongoEngine的维护者,使用disconnect而不是close - bagerard
这并不真实,在文档中明确提到了: :meth:`MongoClient.disconnect`方法已被删除;它是 :meth:`~pymongo.MongoClient.close`的同义词。 - maor10

4

可以使用以下方式通过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 

0
根据mongoengine文档
Calling disconnect() without argument will disconnect the “default” connection

正如已接受的答案所指出的,在某些情况下,使用connect和disconnect时定义“别名”非常重要。

未定义“别名”的实验

在我的情况下,使用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'后,断开连接时一切正常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接