-
-
Save syfun/9615ed40d7d5761281c8ff92fd490b82 to your computer and use it in GitHub Desktop.
Wrapper for pymongo to integrate nicer into Django with failover stuff, forked for python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
MONGODB = { | |
'default': { | |
'NAME': env('MONGODB_DEFAULT_DATABASE', default='scanvis'), # Default database to connect to | |
'URI': env('MONGODB_URI', default='mongodb://localhost:27017/') | |
} | |
} | |
""" | |
from django.conf import settings | |
from pymongo import MongoClient | |
__all__ = ("clients", "client", "db") | |
class DatabaseConfigDoesNotExist(Exception): | |
pass | |
class ClientWrapper(object): | |
def __init__(self, client, default=None): | |
self._client = client | |
self._databases = {} | |
self._default = default | |
def __getattr__(self, alias): | |
if self._default and alias == "default": | |
alias = self._default | |
if alias in self._databases: | |
return self._databases[alias] | |
database = self._client[alias] | |
self._databases[alias] = database | |
return database | |
def __str__(self): | |
return "<ClientWrapper %s>" % self._client.__str__() | |
class MongoHandler: | |
def __init__(self, databases): | |
self.databases = databases | |
self.clients = {} | |
def __getitem__(self, alias): | |
if alias in self.clients: | |
return self.clients[alias] | |
if alias not in self.databases: | |
raise DatabaseConfigDoesNotExist( | |
"The database %s config doesn't exist" % alias | |
) | |
client = MongoClient(self.databases[alias]["URI"]) | |
self.clients[alias] = ClientWrapper(client, self.databases[alias]["NAME"]) | |
return self.clients[alias] | |
clients = MongoHandler(settings.MONGODB) | |
client = clients["default"] | |
db = client.default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment