zoukankan      html  css  js  c++  java
  • python练习题-day11

    1、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),

    要求:登录成功一次,后续的函数都无需再输入用户名和密码
    flag=False
    def wrapper(fun):
        def inner(*args,**kwargs):
            global flag
            if flag==True:
                res=fun(*args,**kwargs)
                return res
            if flag==False:
                count=0
                while count<3:
                    uname=input("请输入用户名:")
                    pwd=input("请输入密码:")
                    f1=open("info_database",encoding="utf-8") #打开存储类型为字典的一个文件
                    data=f1.read()
                    if eval(data).get(uname)==pwd:
                        res=fun(*args,**kwargs)
                        flag=True
                        return res
    
                    else:
                        print("用户名或密码错误,请重新输入(你还有%s次机会)"%(2-count))
                        count+=1
        return inner
    @wrapper
    def goods_add():
        print("购买商品")
    @wrapper
    def good_del():
        print("删除商品")
    2.编写装饰器,为多个函数加上记录调用功能,要求每次调用函数都将被调用的函数名称写入文件
    def wrapper(fun):
        def inner(*args,**kwargs):
            with open("log.txt","a",encoding="utf-8") as f1:
                f1.write(fun.__name__+"
    ")
    
            res=fun(*args,**kwargs)
            return res
        return inner
    @wrapper
    def good_add():
        print("购买商品")
    
    good_add()
    good_add()
     

    3、进阶作业(选做):

    1.编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
    2.为题目1编写装饰器,实现缓存网页内容的功能:
    # 具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中

    import os
    from urllib.request import urlopen
    def cache(func):
        def inner(*args,**kwargs):
            if os.path.getsize('web_cache'):
                with open('web_cache','rb') as f:
                    return f.read()
            ret = func(*args,**kwargs)  #get()
            with open('web_cache','wb') as f:
                f.write(b'*********'+ret)
            return ret
        return inner
    
    @cache
    def get(url):
        code = urlopen(url).read()
        return code
  • 相关阅读:
    106. Construct Binary Tree from Inorder and Postorder Traversal
    105. Construct Binary Tree from Preorder and Inorder Traversal
    449. Serialize and Deserialize BST
    114. Flatten Binary Tree to Linked List
    199. Binary Tree Right Side View
    173. Binary Search Tree Iterator
    98. Validate Binary Search Tree
    965. Univalued Binary Tree
    589. N-ary Tree Preorder Traversal
    eclipse设置总结
  • 原文地址:https://www.cnblogs.com/fumy/p/10352731.html
Copyright © 2011-2022 走看看