Ai
2 Star 0 Fork 1

jackfrued/python2004

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
example23.py 1.92 KB
一键复制 编辑 原始数据 按行查看 历史
jackfrued 提交于 2020-12-07 14:50 +08:00 . 上下文管理器的使用
import contextlib
import random
import time
from functools import wraps
from utils import connect
# 参数化的装饰器(可以通过传参定制你的装饰器)
def record_time(write_log):
# 装饰器:传入被装饰的函数,返回带装饰功能的函数 ---> 代理模式
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
write_log(func.__name__, end - start)
return result
return wrapper
return decorator
def log_to_console(fname, duration):
print(f'{fname}函数执行了{duration:.3f}秒')
def log_to_file(fname, duration):
with open('mydata.log', 'a') as file:
file.write(f'{fname}函数执行了{duration:.3f}\r\n')
def log_to_db(fname, duration):
conn = connect(database='hrs')
try:
with conn.cursor() as cursor:
cursor.execute(
'insert into tb_log values (default, %s, %s)',
(fname, duration)
)
conn.commit()
finally:
conn.close()
@record_time(log_to_db)
def download(filename):
print(f'开始下载{filename}')
time.sleep(random.randint(3, 8))
print(f'{filename}函数下载完成')
# @record_time(log_to_console)
def fac(num):
if num == 0:
return 1
return num * fac(num - 1)
@contextlib.contextmanager
def display_execution_time(fname, write_log):
start = time.time()
yield 'hello'
end = time.time()
write_log(fname, end - start)
with display_execution_time(fac.__name__, log_to_file) as message:
print(message)
result = fac(10)
print(result)
# # download = record_time(download)
# print(download.__name__)
# download('Python从入门到住院.avi')
# # 还原成原始的download函数(取消装饰器)
# download = download.__wrapped__
# download('东京有点热.avi')
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/jackfrued/python2004.git
git@gitee.com:jackfrued/python2004.git
jackfrued
python2004
python2004
master

搜索帮助