Last active
June 23, 2017 01:57
-
-
Save gyli/dbe99aad7333c7a85e7a36f69414ce59 to your computer and use it in GitHub Desktop.
Lazy DB Connection in Python
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
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