Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Created April 6, 2016 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miraculixx/9c0ae88e65e5b67645acec1deeb7b8ff to your computer and use it in GitHub Desktop.
Save miraculixx/9c0ae88e65e5b67645acec1deeb7b8ff to your computer and use it in GitHub Desktop.
straight forward django database adapter for mongoengine
# mongoengine's database instance
import urlparse
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
# cached mongodb instances, by alias
_mongodb = {}
def connect(alias='mongodb'):
"""
straight forward django database adapter for mongodb
requires mongoengine
This will define a mongodb connection with deferred access. Place
somewhere loaded on startup, or use within code where needed. Connections
are pooled by mongoengine.
Usage:
# settings
DATABASES = {
'mongodb' : {
'URL' : 'mongodb://host:port/database',
'OPTIONS' : {
'param' : 'value'
}
}
}
instead of 'mongodb' any other alias can be used. multiple aliases
are supported. If not configured, the default database is
mongodb://localhost/django
OPTIONS is optional. specify any kwargs that
mongoengine.connect() supports. If not specified the following
defaults are applied:
connect=False # defer connection until first access
serverSelectionTimeoutMS=2500 # fail fast if connection is not available
"""
try:
import mongoengine # @UnresolvedImport
except:
raise ImproperlyConfigured(
"Cannot import mongoengine. Is it installed?")
_db = _mongodb.get(alias)
if _db is not None:
return _db
default_config = {
'URL': 'mongodb://localhost/django',
}
dbconfig = settings.DATABASES.get(alias, default_config)
try:
mongo_url = dbconfig.get('URL')
parsed_url = urlparse.urlparse(mongo_url)
database_name = parsed_url.path[1:]
except Exception as e:
msg = "Cannot get or parse URL in settings.DATABASES['%s'], %s" % (
alias, e)
raise ImproperlyConfigured(msg)
# connect via mongoengine
# note this uses a MongoClient in the background, with pooled
# connections. there are multiprocessing issues with pymongo:
# http://api.mongodb.org/python/3.2/faq.html#using-pymongo-with-multiprocessing
# connect=False is due to https://jira.mongodb.org/browse/PYTHON-961
# this defers connecting until the first access
# serverSelectionTimeoutMS=2500 is to fail fast, the default is 30000
options = dbconfig.get('OPTIONS', {})
options.setdefault('connect', False)
options.setdefault('serverSelectionTimeoutMS', 2500)
_db = getattr(mongoengine.connect(database_name,
host=mongo_url,
alias=alias,
**options),
database_name)
# cache db instance
_mongodb[alias] = _db
return _db
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment