2020Python exercise 14 - decorator

@2020.3.23

After class exercise - decorator

1: Write the function, (the time of function execution is simulated by time.sleep(n))

import time
def index(x,y):
    time.sleep(3)
    print('index %s %s' %(x,y))

index(111,222)

 

2: Write decorator to add statistical time to function

import time

def index(x,y):
    start=time.time()
    time.sleep(3)
    print('index %s %s' %(x,y))
    stop = time.time()
    print(stop - start)

index(111,222)

 

3: Write decorator to add authentication function to function

def auth(func):
    def wrapper(*args, **kwargs):
        # 1,Call the original function
        # 2,Add new features to it
        name = input('your name>>: ').strip()
        pwd = input('your password>>: ').strip()
        if name == 'egon' and pwd == '123':
            res = func(*args, **kwargs)
            return res
        else:
            print('Account password error')

    return wrapper


@auth
def index():
    print('from index')

index()

 

4: Write a decorator to add the authentication function for multiple functions (the user's account password comes from a file). The login is required to be successful once, and subsequent functions do not need to enter the user name and password again
Note: to read the dictionary in string form from the file, you can use eval('{"name":"egon","password":"123"}') to convert it to dictionary format

db='db.txt'
login_status={'user':None,'status':False}
def auth(auth_type='file'):
    def auth2(func):
        def wrapper(*args,**kwargs):
            if login_status['user'] and login_status['status']:
                return func(*args,**kwargs)
            if auth_type == 'file':
                with open(db,encoding='utf-8') as f:
                    dic=eval(f.read())
                name=input('username: ').strip()
                password=input('password: ').strip()
                if name in dic and password == dic[name]:
                    login_status['user']=name
                    login_status['status']=True
                    res=func(*args,**kwargs)
                    return res
                else:
                    print('username or password error')
            elif auth_type == 'sql':
                pass
            else:
                pass
        return wrapper
    return auth2

@auth()
def index():
    print('index')

@auth(auth_type='file')
def home(name):
    print('welcome %s to home' %name)


index()
home('mili')

 

5: Write a decorator to add authentication function to multiple functions. The login is required to succeed once. There is no need to log in repeatedly within the timeout period. If the timeout period is exceeded, you must log in again

import time,random
user={'user':None,'login_time':None,'timeout':0.000003,}

def timmer(func):
    def wrapper(*args,**kwargs):
        s1=time.time()
        res=func(*args,**kwargs)
        s2=time.time()
        print('%s' %(s2-s1))
        return res
    return wrapper


def auth(func):
    def wrapper(*args,**kwargs):
        if user['user']:
            timeout=time.time()-user['login_time']
            if timeout < user['timeout']:
                return func(*args,**kwargs)
        name=input('name>>: ').strip()
        password=input('password>>: ').strip()
        if name == 'egon' and password == '123':
            user['user']=name
            user['login_time']=time.time()
            res=func(*args,**kwargs)
            return res
    return wrapper

@auth
def index():
    time.sleep(random.randrange(3))
    print('welcome to index')

@auth
def home(name):
    time.sleep(random.randrange(3))
    print('welcome %s to home ' %name)

index()
home('mili')

 


6: Choose a question
#Thinking questions (optional), superimpose multiple decorators, loading sequence and running sequence. You can superimpose the above realized decorators and verify by yourself
#@ deco1 ා index = deco1 (memory address of deco2.wrapper)
#@ deco2 ා deco2.wrapper's memory address = deco2(deco3.wrapper's memory address)
#Memory address of @ deco3 ා deco3.wrapper = deco3(index)
# def index():
# pass

Tags: Python encoding SQL

Posted on Mon, 23 Mar 2020 07:56:58 -0700 by johnoc