• 将登陆、注册、文件开关设计成函数
  • 将功能的名称与对应的内存地址存储在字典
  • 通过有参装饰器实现登陆验证功能
"""
用户登陆、注册功能
使用函数及修饰器实现
"""

import time
from functools import wraps
import random

def name_pwd(txt,mode1="rt",encoding1="utf-8"):
    # 打开用户信息字典
    with open(txt,mode1,encoding=encoding1) as f:
        info_dic = eval(f.read())
    return info_dic

def name_writte(txt,dic,mode2="wt",encoding2="utf-8"):
    # 用户信息写回文件
    with open(txt,mode2,encoding=encoding2) as f:
        f.write(str(dic))

def login(name,pwd,dic):
    # 用户登陆
    if name == "0" or pwd == "0":
        exit()
    if name in dic.values() and pwd in dic.values():
        print("登陆成功!")
        return False
    else:
        print("用户名或者密码错误!")
        return True

def register(name,pwd,dic):
    # 用户注册
    if name == "0" or pwd == "0":
        exit()
    if name in dic.values() :
        print("用户名重复,请重新输入!")
        return True
    else:
        dic["name"] = name
        dic["pwd"] = pwd
        print("注册成功!")
        return False
    # return dic

fungc_dic = {
    "0":["退出",0],
    "1":["登陆",login],
    "2":["注册",register],
}

def print1(dic):
    for i in dic:
        print("{}:{}".format(i,dic[i][0]))

# 登陆装饰器
def yuser(txt):
    print1(fungc_dic)
    mode = input("请输入模式!")
    def outter(func):
        def wrapper(*args,**kwargs):
            res1 = name_pwd(txt)
            tag = True
            while tag:
                if mode == "0":
                    exit()
                elif mode == "1":
                    name = input("请输入用户名>>>")
                    pwd = input("请输入密码>>>")
                    tag = login(name,pwd,res1)
                elif mode == "2":
                    name = input("请输入用户名>>>")
                    pwd = input("请输入密码>>>")
                    tag = register(name,pwd,res1)
                else:
                    print("指令错误!")
                    continue
            name_writte(txt,res1)
            func(*args,**kwargs)
        return wrapper
    return outter

def timmer(s):
    def outter(func):
        def wrapper(*args,**kwargs):
            start = time.time()
            res = func(*args,**kwargs)
            end = time.time()
            s1 = end - start
            
@yuser("账号密码.txt")
def f1():
    print("hhhhh")

f1()

 

版权声明:本文为zhangchengchao123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zhangchengchao123/p/14597354.html