# 编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
# 注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
default = None
def check1(**kwargs):
def check(func):
def inner():
global default
if default == None:
if kwargs['name'] == 'egon' and kwargs['password'] == '123':
print('认证成功')
re = func()
default = 1
return re
else:
print('已认证')
re = func()
return re
#return
return inner
return check
d = eval('{"name":"egon","password":"123"}')
#d = {"name":"egon","password":"123"}
@check1(**d)
def func():
print('hello world')
@check1()
def func1():
print('123')
@check1()
def func2():
print('456')
func()
func1()
func2()
# 1.编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
def dl(url):
x = '下载页面结果'
return x
# 2.为题目五编写装饰器,实现缓存网页内容的功能:
# 具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中
import os
def swap(func):
def inner(*args):
if os.path.getsize('1.txt') != 0:
with open('1.txt', 'r', encoding='utf-8') as f:
#f.seek(0)
for line in f:
print(line,end='')
else:
re = func(*args)
with open('1.txt','w',encoding='utf-8') as f1:
f1.write(re)
return inner
@swap
def dl(url):
x = url
return x
dl('www.baidu.com')