Made connection lazy
This commit is contained in:
parent
4ae21a671d
commit
196f4471be
@ -38,6 +38,8 @@ Fields
|
||||
|
||||
.. autoclass:: mongoengine.FloatField
|
||||
|
||||
.. autoclass:: mongoengine.BooleanField
|
||||
|
||||
.. autoclass:: mongoengine.DateTimeField
|
||||
|
||||
.. autoclass:: mongoengine.EmbeddedDocumentField
|
||||
|
@ -10,6 +10,10 @@ _connection_settings = {
|
||||
'pool_size': 1,
|
||||
}
|
||||
_connection = None
|
||||
|
||||
_db_name = None
|
||||
_db_username = None
|
||||
_db_password = None
|
||||
_db = None
|
||||
|
||||
|
||||
@ -19,14 +23,30 @@ class ConnectionError(Exception):
|
||||
|
||||
def _get_connection():
|
||||
global _connection
|
||||
# Connect to the database if not already connected
|
||||
if _connection is None:
|
||||
_connection = Connection(**_connection_settings)
|
||||
try:
|
||||
_connection = Connection(**_connection_settings)
|
||||
except:
|
||||
raise ConnectionError('Cannot connect to the database')
|
||||
return _connection
|
||||
|
||||
def _get_db():
|
||||
global _db
|
||||
global _db, _connection
|
||||
# Connect if not already connected
|
||||
if _connection is None:
|
||||
_connection = _get_connection()
|
||||
|
||||
if _db is None:
|
||||
raise ConnectionError('Not connected to database')
|
||||
# _db_name will be None if the user hasn't called connect()
|
||||
if _db_name is None:
|
||||
raise ConnectionError('Not connected to the database')
|
||||
|
||||
# Get DB from current connection and authenticate if necessary
|
||||
_db = _connection[_db_name]
|
||||
if _db_username and _db_password:
|
||||
_db.authenticate(_db_username, _db_password)
|
||||
|
||||
return _db
|
||||
|
||||
def connect(db, username=None, password=None, **kwargs):
|
||||
@ -35,12 +55,8 @@ def connect(db, username=None, password=None, **kwargs):
|
||||
the default port on localhost. If authentication is needed, provide
|
||||
username and password arguments as well.
|
||||
"""
|
||||
global _db
|
||||
|
||||
global _connection_settings, _db_name, _db_username, _db_password
|
||||
_connection_settings.update(kwargs)
|
||||
connection = _get_connection()
|
||||
# Get DB from connection and auth if necessary
|
||||
_db = connection[db]
|
||||
if username is not None and password is not None:
|
||||
_db.authenticate(username, password)
|
||||
|
||||
_db_name = db
|
||||
_db_username = username
|
||||
_db_password = password
|
||||
|
Loading…
x
Reference in New Issue
Block a user