【问题标题】:MongoEngine: Close connectionMongoEngine:关闭连接
【发布时间】:2017-10-07 13:05:08
【问题描述】:

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

【问题讨论】:

    标签: python connection mongoengine disconnect


    【解决方案1】:

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

    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】:

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

      【讨论】:

      • 这里是mongoengine的维护者,使用disconnect而不是close
      • 这不是真的,在文档中:The :meth:`MongoClient.disconnect` method is removed; it was a synonym for :meth:`~pymongo.MongoClient.close
      【解决方案3】:

      它可以通过如下所示的 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 
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2018-08-29
          • 2011-12-08
          • 2019-07-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多