Skip to content

Instantly share code, notes, and snippets.

@alejandrobernardis
Created November 29, 2013 17:15
Show Gist options
  • Save alejandrobernardis/7708929 to your computer and use it in GitHub Desktop.
Save alejandrobernardis/7708929 to your computer and use it in GitHub Desktop.
DB CNX
def db(self, database=None):
_ref = None
_settings = self.settings.get('database')
if _settings:
if database:
_databases = _settings.get('databases')
if database not in _databases:
raise KeyError('Database "%s" is not supported.' % database)
database = _databases.get(database)
else:
database = _settings.get('database')
if 'hosts_or_uri' not in _settings:
raise KeyError('Hosts or Uri is not defined.')
elif not getattr(self, '_database_config'):
_config = copy.deepcopy(_settings)
for key, value in _config.items():
try:
validate(key, value)
except Exception:
del _config[key]
self._database_config = _config
client = MongoReplicaSetClient(
_settings['hosts_or_uri'], **self._database_config)
if database:
_ref = Database(client, database)
elif not getattr(self, '_database_client'):
_ref = Database(client, database)
self._database_client = _ref
try:
username = _settings.get('username')
password = _settings.get('password')
if username and password:
_ref.authenticate(username, password, database)
except Exception:
raise ValueError('Authentication failure.')
return _ref or self._database_client
raise KeyError('Database is not found.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment