Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoEngine: Close connection

I spent ages trying to find a simple example where MongoEngine was being used and a connection was being closed. Finally figured it out and posting my code.

like image 336
malla Avatar asked May 09 '17 09:05

malla


2 Answers

It can be managed with Connection class like bellow. It creates connection with __enter__ and closes it with __exit__ method.

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

Then you can use it with "with" statement.

from app.connection import Connection

with Connection():
     # do some stuff with db, connection will be closed after with statement
     pass 
like image 124
Konrad Avatar answered Sep 30 '22 18:09

Konrad


I know this is an old question, but if anyone else is searching I figured I'd give an alternate answer.

close() does not actually remove the connection from MongoEngine's connection list. This causes problems when trying to connect to a different database later on.

To solve this I used mongoengine.connection.disconnect (even though it's not listed in __all__). My code looks like this:

from mongoengine import connect
from mongoengine.connection import disconnect

db = connect(alias='some_alias')

{do stuff}

disconnect(alias='some_alias')

You can also leave the alias out as it will default to 'default' in both connect and disconnect.

like image 45
Derek Lopes Avatar answered Sep 30 '22 19:09

Derek Lopes