day 11 - 2 decorator exercise

1. Write a decorator to add the function of authentication to multiple functions (the user's account password comes from a file) and it is required to log in successfully once, and subsequent functions do not need to enter the user name and password again

FLAG = False
def login(func):
    def inner(*args,**kwargs):
        global FLAG
        if FLAG:
            ret = func(*args,**kwargs)
            return ret
        else:
            #Login procedure
            username = input('Please enter the user name:')
            password = input('Please input a password:')
            if username == 'ysg' and password == "275":
                FLAG = True
                ret = func(*args,**kwargs)
                return ret
            else:
                print("Login failed")
    return inner

@login
def shoplist_add():
    print("Add items to cart")

@login
def shoplist_del():
    print("Add items to cart")


shoplist_add()
shoplist_del()

 

2. Write a decorator to add a record call function to multiple functions. It is required to write the name of the called function to a file every time the function is called

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

@log
def shoplist_add():
    print("Bought a product")

@log
def shoplist_del():
    print("Deleted a product")

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

 

Advanced practice:
1. Write the function to download the content of the web page. The required function is: the user passes in a url, and the function returns the result of downloading the page
2. Write a decorator for topic 1 to realize the function of caching web page content:
Specific: the downloaded page is stored in the file. If there is a value in the file (the file size is not 0), the page content will be read in the priority file. Otherwise, it will be downloaded and saved in the file

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)

Tags: Python encoding

Posted on Tue, 03 Dec 2019 01:23:51 -0800 by Quicksilver_0