1.编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),
要求登录成功一次,后续的函数都无需再输入用户名和密码
# FALG = False
# def login(user,passwprd):
# with open('admin',mode='r',encoding='utf-8') as f:
# if f.readline().strip()== user and f.readline().strip() == passwprd:
# return True
# return False
# def wrapper(func):
# def inner(*args,**kwargs):
# global FALG
# if FALG:
# ret = func(*args,**kwargs)
# else:
# user = input("输入用户名")
# password = input("输入密码")
# if login(user,password):
# print('登录成功')
# ret = func(*args, **kwargs)
# FALG =True
# else :
# print('登录失败')
# return
# return ret
# return inner
# @wrapper
# def shop_add():
# print('增加一个商品')
# @wrapper
# def shop_del():
# print('删除一件商品')
# shop_add()
# shop_del()
# shop_del()
# shop_del()
2.编写装饰器,为多个函数加上记录调用功能,要求每次调用都将被调用的函数名写入文件
# def warpper(func):
# def inner(*args,**kwargs):
# with open('log',mode='a',encoding='utf-8') as f:
# f.write(func.__name__+'
')
# ret = func(*args,**kwargs)
# return ret
# return inner
#
# @warpper
# def shop_add():
# print('增加一个商品')
# @warpper
# def shop_del():
# print('删除一件商品')
# shop_add()
# shop_del()
# shop_del()
# shop_del()
3.编写下载网页内容函数,要求用户传入url,函数返回下载页的结果,并且编写装饰器。
具体要求:实现下载的页面存放文件中,如果文件中有值,就从文件中读取内容,否则下载至文件中。
# import os
# from urllib.request import urlopen
# def cache(func):
# def inner(*args,**kwargs):
# if os.path.getsize('cache'):
# with open('cache',mode='rb') as f:
# return f.read()
# ret = func(*args,**kwargs)
# with open('cache',mode='wb') as f:
# f.write('******'.encode('utf-8')+ret)
# return ret
# return inner
#
# @cache
# def get(url):
# code = urlopen(url).read()
# return code
# ret = get("http://www.baidu.com")
# print(ret)
# ret = get("http://www.baidu.com")
# print(ret)