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()

 

posted @ 2015-08-18 23:38  程序猿进化之路  阅读(123)  评论(0)    收藏  举报