day 11 – 2 裝飾器練習

亦雙弓發表於2018-12-04

1、編寫裝飾器,為多個函式加上認證的功能(使用者的賬號密碼來源於檔案)要求登入成功一次,後續的函式都無需再輸入使用者名稱和密碼

FLAG = False
def login(func):
    def inner(*args,**kwargs):
        global FLAG
        if FLAG:
            ret = func(*args,**kwargs)
            return ret
        else:
            #登入程式
            username = input(`請輸入使用者名稱:`)
            password = input(`請輸入密碼:`)
            if username == `ysg` and password == "275":
                FLAG = True
                ret = func(*args,**kwargs)
                return ret
            else:
                print("登入失敗")
    return inner

@login
def shoplist_add():
    print("向購物車中新增物品")

@login
def shoplist_del():
    print("向購物車中新增物品")


shoplist_add()
shoplist_del()
FLAG = False
def login(f):
    def inner(*args,**kwargs):
        #判斷是否以成功登入
        global FLAG
        if FLAG:
            ret = f(*args,**kwargs)
            return
        else: 
            #登入驗證
            use = input(`>>>`)
            pwd = input(`>>>`)
            lis=[]
            with open(`E:/py/info.txt`,`r`,encoding=`utf-8`)as info:
                for i in info:
                   lis.append(i)
            if use == lis[0].strip() and pwd == lis[1].strip():
                print(`登陸成功`)
                FLAG = True
                ret = f(*args,**kwargs)
                return ret
            else:
                print(`登入失敗`)
    return inner

@login
def shoping():
    print(`在購物`)
@login
def money():
    print(`在支付`)

shoping()
money()

 

2、編寫裝飾器,為多個函式加上記錄呼叫功能,要求每次呼叫函式都將被呼叫的函式名稱寫入檔案

def log(func):
    def inner(*arge,**kwargs):
        with open(`E:/py/log/log.txt`,`a`,encoding=`utf-8`) as f:
            f.write(func.__name__ + `
`)
        ret = func(*arge,**kwargs)
        print("")
        return ret
    return inner

@log
def shoplist_add():
    print("購買了一件商品")

@log
def shoplist_del():
    print("刪除了一件商品")

shoplist_add()
shoplist_del()
shoplist_add()
shoplist_del()
shoplist_add()
shoplist_del()

 

進階練習:
1.編寫下載網頁內容的函式,要求功能是:使用者傳入一個url,函式返回下載頁面的結果
2.為題目1編寫裝飾器,實現快取網頁內容的功能:
具體:實現下載的頁面存放於檔案中,如果檔案內有值(檔案大小不為0),就優先檔案中讀取網頁內容,否則,就去下載,然後存到檔案中

import os
from urllib.request import urlopen
def cache(func):
    def inner(*arge,**kwargs):
        if os.path.getsize(`E:/py/log/url.txt`):
            with open ("E:/py/log/url.txt","rb") as f:
                return f.read()
        ret = func(*arge,**kwargs)
        with open(`E:/py/log/url.txt`,`wb`) as f:
            f.write(ret+b"*****")
        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)

相關文章