python – Is it necessary to close MongoDB connections with PyMongo?

Question:

I'm working on a REST API with Python (Flask + MongoDB) and during development I verified that, in no part of the code, I had released the bank's resources.

I've already looked around but I haven't found anything feasible about the best way to work this approach.

I don't know if MongoDB is self-managing in this regard, or if I should programmatically manipulate it. Usually in Java or any other language, using drivers for SGDBs or ORMs, there is a concern to close connections with the database when it is no longer being requested by the application.

For example, my class that provides the connection method looks like this:

from mongoengine import connect
from siava.app.aplicacao.utils.Configuracoes import Configuracoes


class Conexao(object):
    """
    Mantem conexões com o banco de dados
    """

    @classmethod
    def conectar(self):
        config = Configuracoes()

        connect(
            name=config.banco['banco'],
            host=config.banco['host'],
            port=config.banco['porta'],
            username=config.banco['usuario'],
            password=config.banco['senha'])

The mongoengine (which encapsulates PyMongo ) even has the disconnect() method, but in the documentation there is nothing about using it. It may be for internal use and not part of the resource usage interface/api.

With that, the question remains, should I control the release of bank resources or is this somehow managed by MongoDB itself, or even by ODM?

Answer:

A scalable web application shouldn't open a connection to serve every request – instead, the practice is to have a pool of active connections that are reused on every web request.

Since you're using Flask – which brings together a number of approaches related to scalable applications, it has the capabilities to do this, and provide the code that runs in your views (including the code called by them) with a connection instance of that poll.

But if you create your connection "by hand" as you are doing – just following the instructions on the Mongo side, without worrying about the lifecycle of a Flask request or its architecture, you are not taking advantage of these mechanisms.

So, not only can your connection "leak" remaining open without being closed (it is possible that it will be closed, if all references to it run out at the end of a request), but above all, most likely you are using a bunch of resources (CPU, network, time) to create a new connection for each web request. You didn't put the code you use to call the connection creation – you might even be trying to recycle connections between requests – in which case it would be in right way, but it's still a matter of reinventing the wheel.

Having said all that, the correct way to go is to get some package that already does the MongoDB integration with FLask, taking advantage of all the mechanisms of Flask to use a connection poll. For example flask-pymongo , or SQLAlchemy itself, which has some MongoDB support as well.

Scroll to Top
AllEscort