day04 装饰器,生成器,迭代器

  上来讲一堆器,吸取了上次的教训,周六早早睡了。yield没咋听懂,而且作业也没用上,就这样吧。虽然这次讲的东西挺难的吧,但是留的作业还好,模拟博客园。主要功能和上次的购物车差不多,往里面加装饰器,登录认证也讲了一下。日志自己写出来了,剩下的感觉真没啥了。第一次拿一百分吧,要说卡的点的话,算是之前不太明白的while 里面有 for循环吧。代码在笔记本上,下次贴上来。值得一提的是,这次的作业一大半是在北戴河写的,自那之后,出差明显少了很多,也好吧,出去一周,又写不了作业了。

6,编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件,可支持多
账号密码),要求登录成功一次(给三次机会),后续的函数都无需再输入用户名和密码。

flag = False
def wrapper(fn):
    def inner(*args,**kwargs):
        global flag
        if flag:
            print('已自动登录')
            ret = fn(*args, **kwargs)
            return ret
        else:
            f = open('练习6.txt', 'r', encoding='utf-8')
            l = f.readlines()
            print(l)
            count = 3
            while count > 0:
                name = input('请输入用户名:')
                password = input('请输入密码:')
                for i in l:
                    print(i.split())
                    if name == i.split()[0] and password == i.split()[1]:
                        print(' %s 登录成功'%name)
                        flag = True
                        return fn(*args,*kwargs)
                else:
                    if count > 1:
                        print('用户名或密码输入错误,请重新输入!')
                        count -= 1
                        print('您还剩 %s 次机会' % count)
                    else:
                        quit('尝试次数过多,账户存在安全隐患,现已退出')
    return inner

@wrapper
def f1():
    print('函数1')

@wrapper
def f2():
    print('函数2')

@wrapper
def f3():
    print('函数3')


f1()
f2()
f3()

for 和 else对齐,很讲究

 

7,给每个函数写⼀一个记录⽇日志的功能,
功能要求:每⼀一次调⽤用函数之前,要将函数名称,时间节点记录到log的⽇日志中。
所需模块:
import time
struct_time = time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S",struct_time))

import time
struct_time = time.localtime()

def wrapper(fn):
    def inner(*args,**kwargs):
        name = fn.__name__ #拿到函数名
        clock = time.strftime("%Y-%m-%d %H:%M:%S", struct_time) #拿到调用时间
        print('函数名:',name)
        print('调用时间:',clock)
        f = open('练习7.txt','a',encoding= 'utf-8')
        f.write('%s : %s\n'%(name,clock)) #将函数名,调用时间追加到日志文件中
        ret = fn(*args,*kwargs)
        return ret
    return inner

@wrapper
def func():
    print('函数')

func()

模拟博客园

import time
struct_time = time.localtime()
user_info = {'user' : None,'status': False}#存用户名和登录状态

def main():   #首页,进行交互
    l = ['请登录','请注册','文章页面','日记页面',
         '评论页面','收藏页面','注销','退出程序']
    print('欢迎来到博客园首页')
    for i,j in enumerate(l,1):
        print(i,j)
    d = {1:login,2:register,3:article,4:diary,
         5:comment,6:collection,7:logout,8:quit}
    while 1:
        choice = input('请选择:')
        if choice.isdigit():
            choice = int(choice)
            if choice in d.keys():
                return d[choice]()
            else:
                print('请重新输入1-8之间的一个数')
        else:
            print('您的输入有误!请重新输入!')

def log(fn):                    #日志装饰器
    def inner(*args,**kwargs):
        fn_name = fn.__name__   #拿到函数名
        clock = time.strftime("%Y-%m-%d %H:%M:%S", struct_time) #拿到调用时间
        f = open('作业.txt','a',encoding= 'utf-8')
        f.write('%s %s 访问 %s\n'%(clock,user_info['user'],fn_name)) #将函数名,调用时间追加到日志文件中
        ret = fn(*args,*kwargs)
        return ret
    return inner

def status(fn):         #判断登录状态装饰器
    def inner(*args,**kwargs):
        if user_info['user']:
            return fn(*args,**kwargs)
        else:
            print('您还未登录')
            print('正在为您跳转到首页')
            time.sleep(1)
            main()
    return inner

def login():
    count = 3
    f = open('register.txt', encoding='utf-8')
    content = f.readlines()
    while count > 0:
        print('----请登录系统-----')
        name = input('输入您的用户名:').strip()
        password = input('输入您的密码:').strip()
        for i in content:
            if name == i.split()[0] and password == i.split()[1]:
                print('登陆成功')
                user_info['user'] = name
                user_info['status'] = True
                print('正在为您跳转到首页')
                time.sleep(1)
                return  main()
        else:
            count -= 1
            print('用户名或密码错误,还有%s次机会'%count)
            continue

def register():
    dic = {}
    f = open('register.txt', encoding='utf-8')
    content = f.readlines()
    for i in content :
        i = i.split()
        dic[i[0]] = i[1]    #用字典存账户密码
    while 1:
        print('---注册您的账户---')
        account = input('设置用户名:').strip()
        if account in dic.keys():
            print('用户名已被注册,请使用其它用户名')
            continue
        else:
            key = input('请设置密码:').strip()
            f = open('register.txt', 'a', encoding='utf-8')
            f.write('\n%s %s' % (account, key))     #追加至register文件
            f.flush()
            f.close()
            user_info['user'] = account
            user_info['status'] = True
            print('已为您自动登录')
            print('正在跳转到首页...')
            time.sleep(1)
            return main()
@status
@log
def article():
    print('欢迎 %s 用户访问文章页面'%user_info['user'])

@status
@log
def diary():
    print('欢迎 %s 用户访问日记页面'%user_info['user'])

@status
@log
def comment():
    print('欢迎 %s 用户访问评论页面'%user_info['user'])

@status
@log
def collection():
    print('欢迎 %s 用户访问收藏页面'%user_info['user'])


def logout():               #注销,先判断是否登录
    if user_info['status'] == True:
        user_info['status'] = False
        print('已注销')
    else:
        print('您尚未登录')

main()

拖欠许久终于搬运上来了。

import time
struct_time = time.localtime()
user_info = {'user' : None,'status': False}#存用户名和登录状态

def main(): #首页,进行交互
l = ['请登录','请注册','文章页面','日记页面',
'评论页面','收藏页面','注销','退出程序']
print('欢迎来到博客园首页')
for i,j in enumerate(l,1):
print(i,j)
d = {1:login,2:register,3:article,4:diary,
5:comment,6:collection,7:logout,8:quit}
while 1:
choice = input('请选择:')
if choice.isdigit():
choice = int(choice)
if choice in d.keys():
return d[choice]()
else:
print('请重新输入1-8之间的一个数')
else:
print('您的输入有误!请重新输入!')

def log(fn): #日志装饰器
def inner(*args,**kwargs):
fn_name = fn.__name__ #拿到函数名
clock = time.strftime("%Y-%m-%d %H:%M:%S", struct_time) #拿到调用时间
f = open('作业.txt','a',encoding= 'utf-8')
f.write('%s %s 访问 %s\n'%(clock,user_info['user'],fn_name)) #将函数名,调用时间追加到日志文件中
ret = fn(*args,*kwargs)
return ret
return inner

def status(fn): #判断登录状态装饰器
def inner(*args,**kwargs):
if user_info['user']:
return fn(*args,**kwargs)
else:
print('您还未登录')
print('正在为您跳转到首页')
time.sleep(1)
main()
return inner

def login():
count = 3
f = open('register.txt', encoding='utf-8')
content = f.readlines()
while count > 0:
print('----请登录系统-----')
name = input('输入您的用户名:').strip()
password = input('输入您的密码:').strip()
for i in content:
if name == i.split()[0] and password == i.split()[1]:
print('登陆成功')
user_info['user'] = name
user_info['status'] = True
print('正在为您跳转到首页')
time.sleep(1)
return main()
else:
count -= 1
print('用户名或密码错误,还有%s次机会'%count)
continue

def register():
dic = {}
f = open('register.txt', encoding='utf-8')
content = f.readlines()
for i in content :
i = i.split()
dic[i[0]] = i[1] #用字典存账户密码
while 1:
print('---注册您的账户---')
account = input('设置用户名:').strip()
if account in dic.keys():
print('用户名已被注册,请使用其它用户名')
continue
else:
key = input('请设置密码:').strip()
f = open('register.txt', 'a', encoding='utf-8')
f.write('\n%s %s' % (account, key)) #追加至register文件
f.flush()
f.close()
user_info['user'] = account
user_info['status'] = True
print('已为您自动登录')
print('正在跳转到首页...')
time.sleep(1)
return main()
@status
@log
def article():
print('欢迎 %s 用户访问文章页面'%user_info['user'])

@status
@log
def diary():
print('欢迎 %s 用户访问日记页面'%user_info['user'])

@status
@log
def comment():
print('欢迎 %s 用户访问评论页面'%user_info['user'])

@status
@log
def collection():
print('欢迎 %s 用户访问收藏页面'%user_info['user'])


def logout(): #注销,先判断是否登录
if user_info['status'] == True:
user_info['status'] = False
print('已注销')
else:
print('您尚未登录')

main()
posted @ 2018-10-27 19:45  CP喜欢晒太阳  阅读(75)  评论(0)    收藏  举报