‌‌R‌‌‌.
‌‌R‌‌‌.

Reputation: 2954

Taking mongoengine.connect out of the setting.py in django

Most of the blog posts and examples on the web, in purpose of connecting to the MongoDB using Mongoengine in Python/Django, have suggested that we should add these lines to the settings.py file of the app:

from mongoengine import connect
connect('project1', host='localhost')

It works fine for most of the cases except one I have faced recently: When the database is down!

Let say if db goes down, the process that is taking care of the web server (in my case, Supervisord) will stop running the app because of Exception that connect throws. It may try few more times but after its timeout reached, it will stop trying.

So even if your app has some parts that are not tied to db, they will also break down.

A quick solution to this is adding a try/exception block to the connect code:

try:
    connect('project1', host='localhost')
except Exception as e:
    print(e)

but I am looking for a better and clean way to handle this.

Upvotes: 3

Views: 665

Answers (1)

matino
matino

Reputation: 17725

Unfortunately this is not really possible with mongoengine unless you go with the try-except solution like you did.

You could try to connect with pure pymongo version 3.0+ using MongoClient and registering the connection manually in the mongoengine.connection._connection_settings dictionary (quite hacky but should work). From pymongo documentation:

Changed in version 3.0: MongoClient is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into MongoReplicaSetClient: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs.

The MongoClient constructor no longer blocks while connecting to the server or servers, and it no longer raises ConnectionFailure if they are unavailable, nor ConfigurationError if the user’s credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads.

Upvotes: 2

Related Questions