Caching MongoDB connections in Django

I'm using the standard (as opposed to NonRel) version of Django connected to PostgreSQL on top of Apache + mod_wsgi. This setup also connects to MongoDB (some data is saved externally). Right now I have to create a new MongoDB connection for each Django request, and pass it along throughout the call stack to all functions that require access to MongoDB. Is there a way to cache connections between requests?

Edit

At the risk of blasphemy, would a global variable work in this case?

Answers


There are several ways explaining how pymongo can work (or fail) with mod_wsgi, suggested here: http://api.mongodb.org/python/current/faq.html?highlight=wsgi#does-pymongo-work-with-mod-wsgi

In addition you can use some kind of pooling solution, like described here: http://www.mongodb.org/display/DOCS/Notes+on+Pooling+for+Mongo+Drivers

One project that I know already to have pooling is MongoEngine, its a very simple ORM that uses pymongo behind the scenes. You might want to look into it together with the pymongo faq solutions above.


You can instantiate MongoDB connection somewhere and import it as opposed to calling pymongo.connection.Connection() every time you need it. Or you can create a Singleton to do this. Something like this in settings.py.

class ConnectionSingleton(object):
    """Represents a MongoDB connection"""
    conn=None
    def __new__(cls,*args,**kwds):
        if cls.conn is None:
            cls.conn=pymongo.connection.Connection()
        return cls.conn

Wouldn't this solve your problem?


Need Your Help

Checklist for IIS 6/ASP.NET Windows Authentication?

asp.net iis authentication active-directory

I've been having trouble getting my ASP.NET application to automatically log users into the Intranet site I'm building. No matter the googling or the experimentation I applied, there is always a l...

Android Studio Multiple Dex Error

java android jar dex

I looked at the related topics but i couldn't find any solution. First time i run the project, the emulator opened, but then it started to give an error.