Skip to content

Instantly share code, notes, and snippets.

@JohnSundarraj
Last active June 1, 2022 20:05
Show Gist options
  • Save JohnSundarraj/fea3de52236c347a5bb3 to your computer and use it in GitHub Desktop.
Save JohnSundarraj/fea3de52236c347a5bb3 to your computer and use it in GitHub Desktop.
Singleton Database Classes
class MySQL(object):
__Instance = None
# Initializer.
def __init__(self):
if self.__class__.__Instance:
return
else:
self.__class__.__Instance = self
self.Conf = DBConf()['MySQL']
self.Engine = create_engine(
'mysql+mysqldb://'+self.Conf['User']+':'+self.Conf['Password']+'@'+self.Conf['Host']+':'+str(self.Conf['Port'])+'/'+self.Conf['Database']+'?charset=utf8&use_unicode=0',
pool_size=10,
pool_recycle=3600,
max_overflow=0,
echo=False
).connect()
self.Engine.execution_options(autocommit=False)
def __new__(self):
if self.__Instance:
return self.__Instance
else:
return object.__new__(self)
class Redis(object):
_Dict = dict()
def __new__(self):
if 'Instance' in Redis._Dict:
return Redis._Dict['Instance']
else:
self.Conf = DBConf()['Redis']
self.Engine = redis.Redis(connection_pool=redis.ConnectionPool(host=self.Conf['Host'],port=self.Conf['Port'],max_connections=10))
return super(Redis,self).__new__(self)
def __init__(self):
Redis._Dict['Instance'] = self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment