13-引入装饰器 案例

8.1第二回合-引入装饰器-案例

  1. 有某个函数,我希望你帮忙我实现这个函数计算下他得执行时间
def outer(func):
    def inner(*args,**kwargs):
        start = time.time()
        v = func(*args,**kwargs)
        end = time.time()
        print(f"总耗时为:{end - start}")
        return v
    return inner

@outer  # do_something  = outer(do_something)
def do_something():
    result = 0
    for i in range(1000000):
        result = result+i
    return result

data = do_something()
print(data)
  1. 函数的执行,在内部实现,执行5次,将每次的结果获取到并返回
def counter(func):
    def inner(*args, **kwargs):
        result = []
        for i in range(5):  
            res = func(*args, **kwargs)
            result.append(res)
        return result

    return inner

# do_something  = counter(do_something)
@counter  
def do_something():
    result = 0
    for i in range(1000000):
        result = result + i
    return result


data = do_something()
print(data)


  1. 通过requests发送网络请求+网络异常导致失败
# 需要进行安装pip install requests 

import requests

res = requests.get('https://www.pythonav.com', timeout=5)
print(res)

# 通过异常处理

try:
    # 正常执行try里面代码
    res = requests.get('https://www.pythonav.com', timeout=5)
    print('请求成功', res)
except Exception as e:
    # 异常执行exception
    print('异常', e)

  • 装饰器版本-未加重试
import requests
def download(url):
    res = requests.get(url)
    print(res.status_code)
    if res.status_code == 200:
        return '成功'
    return '失败'

text = input('请输入网址:').strip()
result = download(text)
print (reslt)
  • 增加重试版本-未使用装饰器
#未增加重试版本-未使用装饰器

def download(url):
    for i in range(5):
        try:

            res = requests.get(url)
            print(res.status_code)
            if res.status_code == 200:
                return '成功'
            return '失败'
        except Exception as e:
            print('异常重试', e )
            continue
    return '异常'

# text = input('请输入网址:').strip()
text = 'https://www.pythonav.com'
result = download(text)
print(result)
posted @ 2024-09-28 08:35  jhchena  阅读(4)  评论(0编辑  收藏  举报