Skip to content

Instantly share code, notes, and snippets.

@josephmosby
Created March 25, 2015 15:03
Show Gist options
  • Save josephmosby/4497f8a4f675170180ab to your computer and use it in GitHub Desktop.
Save josephmosby/4497f8a4f675170180ab to your computer and use it in GitHub Desktop.
Architecture for declaring a global MongoDB MongoClient in Django
#project/project/__init__.py
import project.settings
import pymongo
THE_MONGO_CLIENT = pymongo.MongoClient(settings.MONGO_HOST, settings.MONGO_PORT)
#project/project/settings.py
INSTALLED_APPS += 'utils'
MONGO_HOST = 'localhost' #default
MONGO_PORT = 27017 #default
#project/utils/mongo_tools.py
from project import THE_MONGO_CLIENT
def get_mongo_db(db_name):
return THE_MONGO_CLIENT[db_name]
#project/app/views.py
# (example)
from utils.mongo_tools import get_mongo_db
def example_view(request):
db = get_mongo_db('a_database')
# do request stuff
@thestick613
Copy link

how does this handle THE_MONGO_CLIENT getting disconnected due to no activity?

@mlgarchery
Copy link

Nice, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment