Skip to content

Instantly share code, notes, and snippets.

@gyli
Last active June 23, 2017 01:57
Show Gist options
  • Save gyli/dbe99aad7333c7a85e7a36f69414ce59 to your computer and use it in GitHub Desktop.
Save gyli/dbe99aad7333c7a85e7a36f69414ce59 to your computer and use it in GitHub Desktop.
Lazy DB Connection in Python
import dictmysql # or whatever db library
class LazyConnector:
def __init__(self, *args, **kwargs):
self.__dict__['__factory'] = dictmysql.DictMySQL
self.__dict__['__con'] = None
self.__dict__['__args'] = args
self.__dict__['__kwargs'] = kwargs
def _add_conn(self):
"""
When getting or setting every attribute, check the connection and build one if it doesn't exist
"""
if self.__dict__.get('__con') is None:
self.__dict__['__con'] = self.__dict__['__factory'](*self.__dict__['__args'], **self.__dict__['__kwargs'])
def __getattr__(self, item):
self._add_conn()
return getattr(self.__dict__['__con'], item)
def __setattr__(self, key, value):
self._add_conn()
setattr(self.__dict__['__con'], key, value)
def close(self):
if self.__dict__.get('__con') is not None:
self.__dict__['__con'].close()
self.__dict__['__con'] = None
# Initialize the connector without making connection to db
conn = LazyConnector(**{'host': 'host', 'user': 'user', 'passwd': 'passwd', 'db': 'db'})
# Build connection when calling
conn.query("SELECT NOW();")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment