使用装饰器减少try ...finally的重复使用
@util.try_except_bskgk def added_user_handle(cur, search_time): added_user_sql = """ select userName, FROM_UNIXTIME(createTime) as createTime from bskcommon.user where date(FROM_UNIXTIME(createTime)) = '%s' and userName != '' """%(search_time) cur.execute(added_user_sql) result = cur.fetchall() all_msg = { 'result': util.mat_yes_added_user(result) } return all_msg
#util.py
def try_except_bsk(func):
def wrap(*args):
try:
conn = linkbsk_db()
cur = conn.cursor()
result = func(cur, *args)
except Exception as e:
result = None
log.logg().error(str(e), exc_info=True)
print str(e)
finally:
cur.close()
conn.close()
return result
return wrap
#不使用装饰器 直接调用函数 在作用上没啥区别
def try_except_bsk(func):
def wrap(*args):
try:
conn = linkbsk_db()
cur = conn.cursor()
# return func(cur, *args) 不能这样写 因为会有很多连接没有关闭
result = func(cur, *args)
except Exception as e:
result = None #必须要有的 没有这句, 假如运行错误的话 就会报错《finally部分的result没有赋值》
log.logg().error(str(e), exc_info=True) #打印出错误的堆栈信息
print str(e)
finally:
cur.close()
conn.close()
return result
return wrap
def test_data(): test_sql = 'select * from user_info limit 1' data = db_queryall_params(util.linkbskgk_db(), test_sql) print data test_data()