Is it necessary to close MongoDB connections with PyMongo?

Posted on

Question :

I’m working on a REST API with Python (Flask + MongoDB) and during development I found that in no part of the code had I freed the resources of the database.

I’ve researched there but found nothing feasible about how to best approach this approach.

I do not know if MongoDB is self-manageable in this, or if I should programmatically manipulate it. Usually in Java or any other language, making use of drivers for SGDBs or ORMs, one has to worry about closing the connections with the bank 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 import Configuracoes

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

    def conectar(self):
        config = Configuracoes()


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

With that, the question remains, should I control the release of bank resources or is it managed in some way by MongoDB itself, or even by the ODM?


Answer :

A scalable WEB application should not open a connection to serve each request – instead, it is a practice to have a set of active connections that are reused for every web request.

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

But if you create your connection “manually” as you are doing – following instructions only from the Mongo side, without worrying about the Flask request life cycle or architecture, you are not taking advantage of of these mechanisms.

So, not only can your connection be “leaked” by remaining open without being closed (it may be closed, all references to it will end at the end of a request), but most likely, you are using a lot of resources (CPU, network, time) to create a new connection for each Web request. You have not put the code you use to call the connection creation – you may even be trying to recycle connections between requests – in this if it would be on the right track, but it’s still a matter of reinventing the wheel.

Having said all that, the correct way to do this is to get some package that already integrates MongoDB with FLask, taking advantage of all the Flask engines to use a poll poll. For example, flask-pymongo , or the SQLAlchemy , which has some support for MongoDB as well.


Leave a Reply

Your email address will not be published. Required fields are marked *