Last active
August 29, 2015 14:03
-
-
Save garrydzeng/087e724abb4a05cd3efe to your computer and use it in GitHub Desktop.
Database factory for DBAPI 2.0
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 configparser | |
class DatabaseFactory(object): | |
def __init__(self, filename, encoding=None): | |
"""instantiate with configuration filename""" | |
self._cache = dict() | |
self._servers = configparser.ConfigParser() | |
self._servers.read(filename, encoding) | |
def __del__(self): | |
"""close all cached connection when deleting""" | |
cache = self._cache | |
for connection in cache.values(): | |
connection.close() | |
def new(self, name): | |
"""always create new connection""" | |
if name not in self._servers: | |
raise KeyError("Server %s not in configuration" % name) | |
server = self._servers[name] | |
driver = __import__(server.get("$"), globals(), locals()) | |
return driver.connect( | |
host= server.get("host"), | |
port= server.getint("port", fallback=3306), | |
database= server.get("database", fallback=None), | |
user= server.get("user", fallback=None), | |
password= server.get("password", fallback=None) | |
) | |
def shared(self, name): | |
"""get connection from cache, create new connection if not exists""" | |
if name not in self._cache: | |
self._cache[name] = self.new(name) | |
return self._cache[name] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment