python 入坑路-day5作业ATM

时间:2022-05-06 21:57:58

需求分析

day5 作业:ATM + 购物商城程序
作者:keven
博客地址:http://www.cnblogs.com/chenkeven/articles/8203383.html
http://www.cnblogs.com/chenkeven/articles/8159442.html
http://www.cnblogs.com/chenkeven/articles/8177087.html
http://www.cnblogs.com/chenkeven/articles/8177948.html
http://www.cnblogs.com/chenkeven/articles/8183543.html

使用说明:运行 login 登陆
后台管理:运行user_manager, 用户:admin 密码:admin



需求分析:
ATM:模拟实现一个ATM + 购物商城程序
额度 15000或自定义
1.实现购物商城,买东西加入 购物车,
2.调用信用卡接口结账
3.可以提现,手续费5%
4.支持多账户登录
5.支持账户间转账
6.记录每月日常消费流水
7.提供还款接口
8.ATM记录操作日志
9.提供管理接口,包括添加账户、用户额度,冻结账户等。。。
10.用户认证用装饰器
标红色没有实现。

流程图

  python 入坑路-day5作业ATM

login

import user_manager
import atm_main
import os,sys

ATM_dir=os.path.dirname(os.path.abspath(__file__))
sys.path.append(ATM_dir)
#
# print(ATM_dir)
# print(sys.path[-1])
#导入日志函数
from ATM_logging import ATM_logger

file_name=r"D:\51cto\day5 作业\ATM\ATM_logging\ATM_LOG"
logger=ATM_logger.login(file_name)

#读取用户信息,成字典

user_info_dict={}
with open("user_info","r",encoding="utf-8") as f:
    for line in f:
        line=line.strip().split(",")
        user_info_dict[line[1]]=line[1:]
#print(user_info_dict)

#{'keven': ['keven', 'abc123', '20000', 'n'], 'zhangsan': ['zhangsan', '123abc', '20000', 'y'],}

def auth(user,passwd,user_info_dict):
    '''
   定 验证用户名,密码,账号是否锁定函数
    '''

    if user in user_info_dict.keys()  and passwd == user_info_dict[user][1]:
        if user_info_dict[user][3]== "y":
            banlance=user_info_dict[user][2]
            logger.info("用户【{}】,成功登陆".format(user))
            res=(user,banlance)
        else:
            logger.info("用户【{}】,被锁定的账号尝试登陆")
            res="账号被锁定,请联系管理员"
    else:
        logger.info("用户【{}】,密码错误".format(user))
        res="用户名,密码错误"
    return res


#用户验证三次
def authed():
    i=0
    while True:
        if i<3:
            print("欢迎登陆ATM购物商城".center(50, "*"))
            user = input("pls input your name:")
            passwd = input("pls input your password:")
            res= auth(user,passwd,user_info_dict)
            if res=="用户名,密码错误":
                print(res)
                i+=1
                #logger.info("用户【{}】,密码错误{}次".format(user,i))
            elif res=="账号被锁定,请联系管理员":

                return res
            else:
                balance=res[1]
                return user,balance
        else:
            res="输入错误3次,账号被锁定"
            user_manager.locked_user(user)
            logger.warning("用户【{}】,密码错误3次,被系统锁定")
            return res

#用户入口
if __name__=='__main__':
    res=authed()
    if res=="账号被锁定,请联系管理员" or res =="输入错误3次,账号被锁定":
        exit(res)
    #print(1,res)
    else:
        user=res[0]
        balance=res[1]
        res=atm_main.main(user,balance)
        print(res)

 ATM_MAIN

import user_manager
import shopping

import os,sys

ATM_dir=os.path.dirname(os.path.abspath(__file__))
sys.path.append(ATM_dir)
#
# print(ATM_dir)
# print(sys.path[-1])
#导入日志函数
from ATM_logging import ATM_logger
file_name=r"D:\51cto\day5 作业\ATM\ATM_logging\ATM_LOG"
logger=ATM_logger.atm_main_log(file_name)

#定义取款函数
def withdraw(user,balance,auth="y"):
    quxian=input("请输入取现金额:")
    if quxian.isdigit():
        quxian=float(quxian)
        balance=float(balance)
        if balance>= quxian*1.05:
            balance=balance-quxian*1.05
            res=user_manager.change_balance(user,str(balance),auth="y")
            logger.info("用户【{}】,取现{}".format(user,balance))
        else:
            res="余额不足"
    else:
        res="输入错误,请重新输入"

    return res

#定义转账函数 ,调用查询,修改余额函数
def transfer(user,banlance):
    zhuan_u=input("请输入要转入的账号:")
    zhuan_n=input("请输入要转账的金额:")
    if zhuan_n.isdigit():
        zhuan_n=float(zhuan_n)
        banlance=float(banlance)
        if banlance >= zhuan_n:
            #调用查询余额函数,获取被转入账号余额,调用修改余额函数,修改被转入账号余额
            zhuan_u_b=user_manager.select_user_status(zhuan_u)[1]
            zhuan_u_b=float(zhuan_u_b)
            zhuan_u_b+=zhuan_n
            #print(zhuan_u_b)
            #调用修改余额函数,给转入账号修改金额
            banlance-=zhuan_n
            res=user_manager.change_balance(user,banlance,auth="y")
            if res=="更新成功":
                res="转账成功"
                logger.info("用户【{}】向用户【{}】转账{}".format(user,zhuan_u,zhuan_n))
    else:
        res="输入金额错误,请重新输入"

    return res

#定义还款函数,调用修改 余额函数
def refund(user,balance):
    refund_n = input("请输入还款金额")
    if refund_n.isdigit():
        #print(type(balance))
        balance=float(balance)
        balance+=float(refund_n)
        #print(balance)
        res=user_manager.change_balance(user,balance,auth="y")
        logger.info("用户【{}】还款{}".format(user, balance))
    else:
        res="输入金额错误,请重新输入"
    return res

#定义用户选择,转发处理
def main(user,balance):
    logger.info("用户【{}】成功登陆".format(user))
    while True:
        function_dict = {
            '1':withdraw,
            '2':transfer,
            '3':refund,
            "4":shopping.shopping,
            "5":user_manager.change_passwd

        }
        print("欢迎登陆ATM购物商城".center(50, "*"))
        print('''
        1.取现
        2.转账
        3.还款
        4.购物商城
        5.修改密码        
        6.退出
        ''')
        user_choice=input("pls input your choice:" )
        if user_choice == "6":
            logger.info("用户【{}】,退出系统")
            exit("谢谢光临ATM购物商城,再见")
        elif user_choice in function_dict:
            res=function_dict[user_choice](user,balance)
        else:
            res="选项错误,请重新输入"
        print(res)

if __name__ == '__main__':
    pass

 shopping

import os,sys

ATM_dir=os.path.dirname(os.path.abspath(__file__))
sys.path.append(ATM_dir)
#
# print(ATM_dir)
# print(sys.path[-1])
#导入日志函数
from ATM_logging import ATM_logger

file_name=r"D:\51cto\day5 作业\ATM\ATM_logging\ATM_LOG"
logger=ATM_logger.shopping(file_name)

#购物商城函数
def shopping(user,balance):
    logger.info("用户【{}】,登陆商城购物".format(user))
    #获取商品清单,成列表
    product_list=[]
    with open("product_list","r",encoding="utf-8") as f:
        for line in f:
            line=line.strip().split(",")
            product_list.append(line)
    #print(product_list)

    #banlance=15000
    shopping_l=[]
    #[['iphonex', '8888'], ['bike', '888'], ['pen', '120'], ['laptop', '6666'], ['car', '666666']]
    while True:
        print("欢迎光临购物商城".center(50,"*"))
        for i,j in enumerate(product_list):
            print(i,j)
        u_choice=input("请输入你要购买商品的序号,或者按'q'退出买单:")
        if u_choice.isdigit():
            balance=float(balance)
            product_price=float(product_list[int(u_choice)][1])
            if balance >= product_price:
                balance-=product_price
                #print(balance)
                shopping_l.append(product_list[int(u_choice)][0])
            else:
                res="余额不足"
                return res
        elif u_choice == "q":
            #print(balance)
            balance=str(balance)
            for i in shopping_l:
                print(i)
            change_balance(user,balance)
            print("谢谢惠顾")
            logger.info("用户【{}】,购买商品{}".format(user,shopping_l))
            break
            #return user,banlance
        else:
            print("请输入正确的选项")


#修改余额
def change_balance(user,balance):
    #print(user,balance)

    with open("user_info", "r", encoding="utf-8") as f:
        with open("new", "w", encoding="utf-8") as f1:
            for line in f:
                line=line.split(",")
                if user in line:
                    line[3]=balance
                    print(balance)
                    line=",".join(line)
                    f1.write(line)
                    res="结账成功"
                else:
                    line = ",".join(line)
                    f1.write(line)
            f1.flush()
            f1.close()

    os.remove("user_info")
    os.rename("new","user_info")
    return res


# if __name__ == '__main__':
#     user_info_dict = {}
#     with open("user_info", "r", encoding="utf-8") as f:
#         for line in f:
#             line = line.strip().split(",")
#             user_info_dict[line[1]] = line[1:]
#     f.close()
#
#     i=0
#     while i < 3:
#         user=input("pls input your username:")
#         passwd=input("pls input your password:")
#         if user in user_info_dict.keys() and passwd == user_info_dict[user][1]:
#             print(user_info_dict[user][3])
#             status=user_info_dict[user][3].strip()
#             if status =="y":
#                 balance = float(user_info_dict[user][2])
#                 #print(balance)
#                 break
#             elif status == "n":
#                 print("账号被锁定,请联系管理员")
#                 break
#         else:
#             print( "用户名密码错误,请重新输入:")
#
#     res= shopping(user,balance)
#     print(res)

user_manager

import os
import sys

ATM_dir=os.path.dirname(os.path.abspath(__file__))
sys.path.append(ATM_dir)
#
# print(ATM_dir)
# print(sys.path[-1])
from ATM_logging import ATM_logger

file_name=r"D:\51cto\day5 作业\ATM\ATM_logging\ATM_LOG"
logger=ATM_logger.user_manager_log(file_name)


def add_user():
    user=input("pls input username:")
    passwd=input("pls input password:")
    balance=input("pls input balance:")
    status="y"
    #u_input=[]
    max_id=0
    title="id,user_name,passwd,balance,status"
    if balance.isdigit():
        with open("user_info","r",encoding="utf-8") as f:
            for line in f:
                f_dict=dict(zip(title.split(","), line.split(",")))
                if user in f_dict.values():
                    res="用户名重复"
                    logger.warning("创建用户{},用户已存在".format(user))
                    return res
    else:
        res = "输入的金额,错误请重新输入!"
        return res

    with open("user_info","a+",encoding="utf-8") as f:
        f.seek(0)
        for line in f:
            f_dict=dict(zip(title.split(","),line.split(",")))
            id=int(f_dict.get("id"))
            max_id=id if max_id< id else max_id
            new_id=str(max_id+1)
        line="{},{},{},{},{}".format(new_id,user,passwd,balance,status)
        f.write("\n{}".format(line))
        f.flush()
        logger.info("创建用户{},成功".format(user))
        res = "用户新增成功"
    return res

def change_balance(user="",balance="",auth="n"):
    if len(user) ==0:
        user = input("pls input username such as:'lisi:")
        balance= input("pls input banlace:")

        user_info_dict = {}
        with open("user_info", "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip().split(",")
                user_info_dict[line[1]] = line[1:]
                if user not in user_info_dict.keys():
                    logger.warning("修改{}的余额,用户不存在".format(user))
                    res="账号不存在"
                    return res
                else:
                    auth="y"

    if auth=="y":
        #print(user,balance)
        try:
            float(balance) or int(balance)
            f_flag=True
        except:
            f_flag=False


        #print(f_flag,)
        if f_flag:
            balance=str(balance)
            with open("user_info","r",encoding="utf-8") as f:
                with open("user_info_new", "w", encoding="utf-8") as f1:
                    for line in f:
                        line=line.split(",")
                        if user in line:
                            line[3]=balance
                            line=",".join(line)
                            f1.write(line)

                        else:
                            line = ",".join(line)
                            f1.write(line)
                    f1.flush()

            os.remove("user_info")
            os.rename("user_info_new","user_info")
            logger.info("成功修改用户【{}】的金额为【{}】".format(user,balance))
            res = "更新成功"
            return res
        else:
            logger.critical("输入的金额{},不符合格式".format(balance))
            res="输入金额错误,请重新输入"
            return res
    #res=2


# def select_user_banlace(user):
#     if len(user) == 0:
#         user=input("pls input user:")
#     with open("user_info","r",encoding="utf-8") as f:
#         for line in f:
#             line=line.split(",")
#             if user in line:
#                 banlance=line[3]
#                 return banlance
#         f.close()

def change_passwd(user="",*args):
    if len(user) ==0:
        user = input("pls input username such as:'lisi:")

        user_info_dict = {}
        with open("user_info", "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip().split(",")
                user_info_dict[line[1]] = line[1:]
                if user not in user_info_dict.keys():
                    logger.warning("修改{}的密码,用户不存在".format(user))
                    res="账号不存在"
                    return res
                else:
                    auth="y"

    else:
        passwd = input("pls input new password:")

        with open("user_info","r",encoding="utf-8") as f:
            with open("user_info_new", "w", encoding="utf-8") as f1:
                for line in f:
                    line=line.split(",")
                    if user in line:
                        line[2]=passwd
                        line=",".join(line)
                        f1.write(line)

                    else:
                        line = ",".join(line)
                        f1.write(line)
                f1.flush()

        os.remove("user_info")
        os.rename("user_info_new","user_info")
        logger.info("成功修改用户【{}】的密码".format(user))
        res = "更新成功"
        return res


def select_user_status(user=""):
    if len(user) == 0:
        user=input("pls input name:")
        #打印账号状态
    with open("user_info","r",encoding="utf-8") as f:
        for line in f:
            line=line.split(",")
            #print(u_input,line)
            if user in line:
                res=(user,line[3],line[4].strip(),"y:账号活动,n:账号锁定")
                logger.info("查询{}的状态".format(user))
                return res
        else:
            logger.warning("查询{}的状态,用户不存在".format(user))
            res="账号不存在"
        f.close()
    #res=3
    return res

def locked_user(user="",status="n"):
    if len(user) == 0:
        user=input("pls input username:")
        status=input("pls input status:,status such as:y (y:激活账号,n:锁定账号):")

    l=[]
    with open("user_info","r",encoding="utf-8") as f:
        for line in f:
            line=line.split(",")
            #print(line)
            l.extend(line)

    #print(l)
    if user not in l:
        res="账号不存在"
        return res
    else:
        with open("user_info","r",encoding="utf-8") as f:
            with open("user_info_new","w",encoding="utf-8") as f1:
                for line in f:
                    line=line.split(",")
                    #print(u_input,line)
                    if user in line:
                        line[4]=status
                        line=",".join(line)
                        f1.write("{}\n".format(line))
                    else:
                        line=",".join(line)
                        f1.write(line)
                f1.flush()
        os.remove("user_info")
        os.rename("user_info_new", "user_info")
        if status == "y":
            logger.info("成功激活账号:【{}】".format(user))
            res="账号已激活"
        elif status == "n":
            logger.info("成功锁定账号:【{}】".format(user))
            res="账号已锁定"

    return res

if __name__ == '__main__':
    print("\033[01;42mwelcome user manager\033[0m".center(50, "*"))
    user = input("pls input administrator account:")
    passwd = input("pls input password:")
    if user == "admin" and passwd == "admin":
        logger.info("管理员:admin,成功登陆")
        while True:
            # user=input("pls input administrator account:")
            # passwd=input("pls input password:")

            function_dict={
                '1':add_user,
                '2':change_balance,
                '3':locked_user,
                '4':select_user_status,
                "5":change_passwd

            }
            print('''
            1.新增用户
            2.修改余额
            3.冻结\激活账号
            4.查询账号
            5.修改密码
            6.退出系统
            ''')
            user_choice=input("pls input your choice:")
            if user_choice == "6":
                logger.info("管理员:admin,退出系统")
                exit("再见")
            elif user_choice in function_dict:
                res=function_dict[user_choice]()
            else:
                res="输入错误请重新输入"
            print(res)
        else:
            exit("用户名密码错误")

 logger

import logging
import os,sys

# ATM_dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.append(ATM_dir)
# # print(sys.path)
# # print(ATM_dir)
# print(os.path.abspath(__file__))
#定义后台管理收集日志函数
def user_manager_log(file_name):
    logger = logging.getLogger("u_m_log")
    logger.setLevel(logging.DEBUG)

    fh=logging.FileHandler(file_name,encoding="utf-8")

    fh.setLevel(logging.DEBUG)

    fh_formatter = logging.Formatter("%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s")
    fh.setFormatter(fh_formatter)

    logger.addHandler(fh)

    return logger

def atm_main_log(file_name):
    logger = logging.getLogger("A_M_LOG")
    logger.setLevel(logging.DEBUG)

    fh = logging.FileHandler(file_name, encoding="utf-8")

    fh.setLevel(logging.DEBUG)

    fh_formatter = logging.Formatter("%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s")
    fh.setFormatter(fh_formatter)

    logger.addHandler(fh)

    return logger

def shopping(file_name):
    logger = logging.getLogger("shopping_log")
    logger.setLevel(logging.DEBUG)

    fh=logging.FileHandler(file_name,encoding="utf-8")

    fh.setLevel(logging.DEBUG)

    fh_formatter = logging.Formatter("%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s")
    fh.setFormatter(fh_formatter)

    logger.addHandler(fh)

    return logger

def login(file_name):
    logger = logging.getLogger("login_log")
    logger.setLevel(logging.DEBUG)

    fh=logging.FileHandler(file_name,encoding="utf-8")

    fh.setLevel(logging.DEBUG)

    fh_formatter = logging.Formatter("%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s")
    fh.setFormatter(fh_formatter)

    logger.addHandler(fh)

    return logger

if __name__=='__main__':
    file_name = r"D:\51cto\day5 作业\ATM\ATM_logging\user_manager_LOG"
    logger=user_manager_log(file_name)

    logger.info("牛逼")
    logger.debug("debug")
    logger.warning("warning")
    logger.error("error")
    logger.critical("critical")

 user_info

1,keven,abc123,1111.0,y
2,zhangsan,abc123,11007.0,y
3,lisi,hah123,15000,y
4,haha,abc123,15000,n
5,hehe,hehe1,15000,y
6,h,h,19000,y

 product_list

iphonex,8888
bike,888
pen,120
laptop,6666
car,666666