三个作业:

# 1.编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
login_dic = {'alex':False}
def login(func):
    def inner(*args,**kwargs):
        if not login_dic['alex']:
            usrname = input('用户名 : ')
            passwd = input('密  码 : ')
            with open('userinfo') as f:
                for line in f:
                    line = line.strip()
                    usr,pwd = line.split(' ')
                    if usrname.strip() == usr and passwd.strip() == pwd:
                        print('登陆成功')
                        login_dic[usrname] = True
        if login_dic['alex']:
            ret = func(*args,**kwargs)
            return ret
    return inner

@login
def home():
    print('欢迎来到home页')

# home()
# home()
# home()
# 2.编写装饰器,为多个函数加上记录调用功能,要求每次调用函数都将被调用的函数名称写入文件
def log(func):
    def inner(*args,**kwargs):
        with open('func.log','a+',encoding='utf-8') as f:
            f.write('%s被调用了\n'%func.__name__)
        ret = func(*args,**kwargs)
        return ret
    return inner

@log
def func1():
    print('我是func1')

@log
def func2():
    print('我是func2')

func1()
func1()
func2()

#如果这个网页没有被爬取过,就真的去访问这个网页,否则,返回之前访问的时候存在文件中的内容
from urllib.request import urlopen

def wrapper(func):
    def inner(*args,**kwargs):
        with open('web','rb') as f:
            web_content = f.read()
        if not web_content:
            web_content = func(*args,**kwargs)
            with open('web','wb') as f:
                f.write(b'aaaaaaaaa'+web_content)
        return web_content
    return inner

# @wrapper
def get_url(url):
    content = urlopen(url).read()
    return content

web_content = get_url('http://www.cnblogs.com/Eva-J/articles/7213953.html')
print(web_content)
# web_content = get_url('http://www.cnblogs.com/Eva-J/articles/7213954.html')
# print(web_content)
# web_content = get_url('http://www.cnblogs.com/Eva-J/articles/7213953.html')
# print(web_content)
#迭代器和生成器



#r 可读    文本操作模式
#w 可写    文本操作模式
#rb 直接操作二进制
#wb 直接操作二进制
# 当你拿到的是纯文字,就用文本操作模式
# 当你拿到的是字节,就用二进制操作的模式

# {'url':'文件名1','url2':''}   os

#装饰器:
    # 在不修改一个函数的调用方式的前提下载一个函数的前后添加功能
#装饰器的本质:闭包函数
装饰器三个作业

相关文章:

  • 2019-03-19
  • 2021-07-03
  • 2021-12-25
  • 2021-08-14
猜你喜欢
  • 2021-07-08
  • 2021-12-19
  • 2022-12-23
  • 2021-08-13
  • 2021-07-02
  • 2021-07-30
相关资源
相似解决方案