Created
August 2, 2013 18:04
-
-
Save ipconfiger/6141996 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
proxies = {} | |
class _ConnectionWrapper(object): | |
""" | |
用来包装Connection的类 | |
""" | |
def __init__(self,conn): | |
self.conn=conn | |
def close(self): | |
""" | |
屏蔽掉关闭连接的行为 | |
""" | |
pass | |
def __getattr__(self,key): | |
""" | |
把其他属性都原封不动的代理出去 | |
""" | |
return getattr(self.conn, key) | |
class _DbWrapper(): | |
""" | |
代理MySQLdb模块的对象 | |
""" | |
def __init__(self,module): | |
self.connection=None #HOLD住的长连接 | |
self.db=module #原始的MySQLdb模块 | |
def __getattr__(self, key): | |
""" | |
代理除connect外的所有属性 | |
""" | |
return getattr(self.db, key) | |
def connect(self,*argv,**kwargv): | |
if not self.connection: | |
self.connection=self.db.connect(*argv,**kwargv) | |
return _ConnectionWrapper(self.connection) | |
def manage(module): | |
try: | |
return proxies[module] | |
except KeyError: | |
return proxies.setdefault(module,_DbWrapper(module)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment