python3闭包函数练习题

作业1

 

编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件)。要求:登录成功一次,后续的函数都无需再输入用户名和密码;注意:从文件中读出字符串形式的字典,可以用以下方式把字典字符串转化成字符串

eval('{"name":"albert","password":"123"}')
db = 'a.txt'
login_status = {'status': False}


def auth(auth_type='file'):
    def auth2(func):
        def wrapper(*args, **kwargs):
            if 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 == dic['name'] and password == dic['password']:
                    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('albert')

 

作业2

 

编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录

import time
import random

user_data = {
    'user': None,
    'login': False,
    'now_time': time.time()
}
db_username = 'albert'
db_password = '123'


def auth(func):
    def wrapper(*args, **kwargs):
        passed_time = time.time() - user_data['now_time']

        if user_data['user'] and passed_time < 3:
            return func(*args, **kwargs)
        else:
            while True:
                username = input('input your username>>:').strip()
                password = input('input your password>>:').strip()
                if username == db_username and password == db_password:
                    print('login successfully')
                    user_data['user'] = username
                    user_data['login'] = True
                    user_data['now_time'] = time.time()
                    return func(*args, **kwargs)
                else:
                    print('username or password is invalid')

    return wrapper


@auth
def index():
    print('This is index page')


@auth
def home(name):
    print('Welcome %s to home page' % name)


index()
time.sleep(random.randint(2, 4))  # create 2-4 random number
home('albert')

 

作业3

 

编写日志装饰器,实现功能:一旦某函数执行,则将函数执行时间写入到日志文件中,日志文件路径可以指定。

注意:时间格式的获取

import time

the_time = time.strftime('%Y-%m-%d %X')
print(the_time)




import time


def add_log(file):
    def wrapper(func):
        def inner(*args, **kwargs):
            with open(file, 'a', encoding='utf-8') as f:
                f.write('[%s]:[%s]\n' % (func.__name__, time.strftime('%Y-%m-%d %X')))
                return func(*args, **kwargs)

        return inner

    return wrapper


@add_log('db1.txt')
def index():
    print('This is index page')


@add_log('db2.txt')
def home(name):
    print('Welcome %s to home page' % name)


index()
home('albert')

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值