Skip to content Skip to sidebar Skip to footer

Where To Store Mongoclient In Django

I'm using pymongo to allow my Django site to save data to MongoDB. Apparently the MongoClient() class has connection pooling built in, and it should only be instantiated once when

Solution 1:

It's a bit late answering this question, but future searchers may find it useful.

If you're only using MongoDB for a few operations (and thus don't want to use the full MongoEngine architecture), you can set up your architecture like this:

# project/settings.py
  (place Mongo connection info here)

# project/__init__.py
  (declare a global MongoClient here, it will be throughout the app)

# project/all apps
  import project.MY_MONGO_CLIENT_NAME
  (useMongoClientasneeded)

A more full breakdown may be found here: https://gist.github.com/josephmosby/4497f8a4f675170180ab

Solution 2:

Further to (and inspired by) josephmosby's answer, I'm using something like the following:

# project/settings

MONGO_DB = {
    'default': {
        'HOST': 'localhost',
        'PORT': 27017
    },
    ...
}

# project/__init__.py

gMongoClient = {}

# project/utils/mongo_tool.pyfrom project import gMongoClient
from project.settings import MONGO_DB
import pymongo

defget_mongo_db(dbname="default"):
    if dbname in gMongoClient:
        return gMongoClient[dbname]

    if dbname in MONGO_DB:
        with MONGO_DB[dbname] as config:
            gMongoClient = pymongo.MongoClient(config["HOST"],
                                               config["PORT"])
    else:
        gMongoClient[dbname] = Nonereturn gMongoClient[dbname]

# .../view.pyfrom utils import mongo_tool
...
db = mongo_tool.get_mongo_db()
results = db["collection"].find(...)

This could be made fancier, e.g. to see if a user and password are specified in the settings for a particular connection, etc., but the above captures the essence of the idea.

Post a Comment for "Where To Store Mongoclient In Django"