2020Python job 15 -- decorator 2 + iterator

Keywords: Python encoding MySQL

@2020.3.24

(Q1)

Homework:
1. Compile the parametric decorator explained in class

def auth(db_type = 'file'):
    def inner(func):
        def wrapper(*args, **kwargs):
            inp_name = input("your name:").strip()
            inp_pwd = input("your password:").strip()
            if db_type == 'file':
                with open(r'db.txt', 'rt', encoding='utf-8') as f:
                    for line in f:
                        user, pwd, *_ = line.strip().split(':')
                        if inp_name == user and inp_pwd == pwd:
                            print('File authentication login succeeded')
                            return func(inp_name)
                    else:
                        print('Wrong user name and password')
            elif db_type == 'mysql':
                func()
            elif db_type == 'ldap':
                func()
            else:
                print('The authentication login method does not exist')
        return wrapper
    return inner
@auth(db_type='file')
def index(name):
    print('welcome [%s]' % name)

@auth(db_type='mysql')
def mysql_login():
    print('mysql Authentication')

@auth(db_type='ldap')
def ldap_login():
    print('ldap Authentication')

index()
mysql_login()
ldap_login()


2: Remember that we use the concept of function object to make a function dictionary operation? Come on, we have a higher approach——

Declare an empty dictionary at the beginning of the file, and then add a decorator before each function to complete the operation of automatically adding to the dictionary

d = {}
key = 0
def add_dict(func):
    def wrapper(*args, **kwargs):
        global key
        d['{}'.format(key)] = func
        key += 1
    return wrapper

@add_dict
def index():
    pass

@add_dict
def home():
    pass

index()
home()

print(d)


3. Write the log decorator to realize the following functions: once function f1 is executed, write the message 2017-07-21 11:12:11 f1 run to the log file. The log file path can be specified
Note: acquisition of time format
import time
time.strftime('%Y-%m-%d %X')

import time
import os

def logger(logfile):
    def deco(func):
        if not os.path.exists(logfile):
            with open(logfile,'w'):pass

        def wrapper(*args,**kwargs):
            res=func(*args,**kwargs)
            with open(logfile,'a',encoding='utf-8') as f:
                f.write('%s %s run\n' %(time.strftime('%Y-%m-%d %X'),func.__name__))
            return res
        return wrapper
    return deco

@logger(logfile='milimili.log')
def index():
    print('index')

index()


4. Based on the way of iterator, the while loop is used to iterate the value of string, list, tuple, dictionary, set and file object

def wrapper(inp_type):
    print('The output content is: {}'.format(type(inp_type)))
    while True:
        try:
            print(next(inp_type))
        except StopIteration:
            break

wrapper('123'.__iter__())
wrapper([1,2,3].__iter__())
wrapper((1,2,3).__iter__())
wrapper({'k1':1,'k2':2}.__iter__())
wrapper({1,2,3}.__iter__())
with open('a.txt', 'rt', encoding='utf-8') as f:
    wrapper(f.__iter__())


5. Implement range function with custom iterator

def my_range(start, stop, step=1):
    while start < stop:
        start += step
        yield start

for i in my_range(0,5):
    print(i-1)

Posted by JayNak on Wed, 25 Mar 2020 07:33:21 -0700