python decorator解析
http://coolshell.cn/articles/11265.html
解释的很清楚
__author__ = 'li' import sys from functools import wraps import MySQLdb class DBConfiguration(object): def __init__(self, env): if env == 'local': #.....
elif env == 'prod': #.....
def mysql(sql): _conf = DBConfiguration("local") def _handle_error(err): print err sys.exit(-1) def decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): mysqlconn = MySQLdb.connect(db=_conf.db, host=_conf.host, port=_conf.port, user=_conf.usr, passwd=_conf.passwd, charset='utf8') cursor = mysqlconn.cursor() try: cursor.execute(sql) rs = cursor.fetchall() except MySQLdb.Error as err: _handle_error(err) kwargs["data"] = rs result = fn(*args, **kwargs) return result return wrapper return decorator @mysql("select * from account") def get_account(data): print data return data get_account()

浙公网安备 33010602011771号