python 购物车+ATM

第一个python项目,很有意思 :)


程序结构图.PNG

# settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
BASE_DB = os.path.join(BASE_DIR, 'db')
##############
# logging配置#
##############
# 定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]'  # 其中name为getLogger()指定的名字;lineno为调用日志输出函数的语句所在的代码行
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
# 定义日志输出格式 结束
logfile_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # log文件的目录,需要自定义文件路径 # atm
logfile_dir = os.path.join(logfile_dir, 'log')  # C:\Users\oldboy\Desktop\atm\log
logfile_name = 'log.log'  # log文件名,需要自定义路径名
# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):  # C:\Users\oldboy\Desktop\atm\log
    os.mkdir(logfile_dir)
# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)  # C:\Users\oldboy\Desktop\atm\log\log.log
# 定义日志路径 结束
# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},  # filter可以不定义
    'handlers': {
        # 打印到终端的日志
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        # 打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path,  # 日志文件
            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M  (*****)
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
        # logging.getLogger(__name__)拿到的logger配置。如果''设置为固定值logger1,则下次导入必须设置成logging.getLogger('logger1')
        '': {
            # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'handlers': ['default', 'console'],
            'level': 'DEBUG',
            'propagate': False,  # 向上(更高level的logger)传递
        },
    },
}
# src.py
from interface import user, bank, shop
from lib import common
user_dic = {
    'name': None
}
def login():
    if user_dic['name']:
        print("\033[31;1m请勿重复登陆\033[0m")
        return
    print("\033[1;33m登陆\033[0m")
    while True:
        name = input("用户名:").strip()
        pwd = input("密码:").strip()
        flag, msg = user.login_interface(name, pwd)
        if flag:
            user_dic['name'] = name
            print(msg)
            break
        else:
            print(msg)
def register():
    if user_dic['name']:
        print("\033[31;1m当前用户已登陆\033[0m")
        return
    print("\033[1;33m欢迎注册\033[0m")
    while True:
        name = input("用户名:").strip()
        pwd = input("密码:").strip()
        conf_pwd = input("确认密码:").strip()
        if pwd == conf_pwd:
            flag, msg = user.register_interface(name, pwd)
            if flag:
                print(msg)
                break
            else:
                print(msg)
        else:
            print("\033[31;1m两次输入不一致\033[0m")
@common.auth
def check_balance():
    print("\033[1;33m查看余额\033[0m")
    balance = bank.check_balance_interface(user_dic['name'])
    print(f"您的余额为:\033[31;1m{balance}\033[0m")
@common.auth
def transfer():
    '''
    转账功能
    :return:
    '''
    print("\033[1;33m转账\033[0m")
    while True:
        print("q退出")
        to_user = input("请输入目标账户:").strip()
        if to_user == 'q':
            break
        money = input("请输入转账金额:").strip()
        if money.isdigit():
            money = int(money)
            flag, msg = bank.transfer_interface(user_dic['name'], to_user, money)
            if flag:
                print(msg)
                break
            else:
                print(msg)
                break
        else:
            print("请输入数字")
@common.auth
def reply():
    print("\033[1;33m还款\033[0m")
    while True:
        own = bank.check_balance_interface(user_dic['name'])
        if own < 0:
            print("您目前欠账:", own)
            reply_money = input("请输入还款金额:").strip()
            if reply_money.isdigit():
                reply_money = int(reply_money)
                msg = bank.reply_interface(user_dic['name'], reply_money)
                print(msg)
                break
            else:
                print("请输入数字")
        else:
            print("您未欠款")
            break
@common.auth
def withdraw():
    '''
    提现功能
    :return:
    '''
    print("\033[1;33m取款\033[0m")
    while True:
        old_balance = bank.check_balance_interface(user_dic['name'])
        print("------您目前可提现的金额为:", old_balance)
        money = input("输入提现金额:").strip()
        if money.isdigit():
            money = int(money)
            flag, msg = bank.withdraw_interface(user_dic['name'], money)
            if flag:
                print(msg)
                break
            else:
                print(msg)
                break
        else:
            print("请输入数字")
@common.auth
def shopping():
    '''
    在电子商场添加产品到购物车,然后在购物车里结账
    :return:
    '''
    print("\033[1;33m欢迎购物\033[0m")
    goods_list = [
        ['oneplus', 10000],
        ['huawei', 6000],
        ['mi', 3000],
        ['oppo', 4000],
        ['vivo',3000]
    ]
    balance = bank.check_balance_interface(user_dic['name'])
    shopping_cart = shop.check_shopping_cart_interface(user_dic['name'])
    while True:
        total_cost = 0
        print("\033[1;33m>>>>>>>>>欢迎来到电子商城 您的余额是 %s 元<<<<<<\033[0m" % (balance))
        print("q退出商城,z结账,a查看购物车")
        for i, goods in enumerate(goods_list):
            print(f"商品编号:{i} 商品:{goods}")  # 打印商品列表,显示商品列表索引
        choice = input("选择对应的商品编号或者功能").strip()
        if len(choice) == 0:  # 判断输入字符串是否为空和字符串长度
            print("---您没有选择商品----")
            continue
        if choice.isdigit():  # 判断输入的choice是不是一个数字
            choice = int(choice)  # 把输入的字符串转成整型
            if 0 <= choice < len(goods_list):  # 输入的整数必须小于商品列表的数量
                goods_name = goods_list[choice][0]
                goods_price = goods_list[choice][1]
                if goods_name not in shopping_cart:  # 将商品加入购物车
                    shopping_cart[goods_name] = {'price': goods_price, 'count': 1}
                else:
                    shopping_cart[goods_name]['count'] += 1
                print(">>>>>>>添加 \033[32;1m%s\033[0m 到购物车" % (goods_name))
            else:
                print("\033[31;1m没有此商品\033[0m")
        elif choice == 'a':
            print("------您的购物车列表----------")
            print(shopping_cart)
        elif choice == 'z':
            print("------您的购物车列表----------")
            if shopping_cart:
                print(shopping_cart)
                for i in shopping_cart.keys():
                    total_cost += shopping_cart[i]['price'] * shopping_cart[i]['count']  # 总价=单价×数量
                print("合计:", total_cost)
                confirm = input("----------!!!!!!!!!!输入\033[31;1m'y'\033[0m确认购买")
                if confirm == 'y':
                    if balance >= total_cost:
                        shopping_cart = {}
                        msg = shop.shopping_interface(user_dic['name'], total_cost, shopping_cart)
                        print("\033[31;1m------------购买成功", msg)
                        break
                    else:
                        if balance < 0:
                            print("----------对不起,您的金额不足,还差 \033[31;1m%s\033[0m--------" % (0 - total_cost))
                        else:
                            print("----------对不起,您的金额不足,还差 \033[31;1m%s\033[0m--------" % (total_cost - balance))
                        tree_pay = input("是否选择\033[31;1m树呗\033[0m付款?(y/n)")
                        if tree_pay == 'y':
                            balance -= total_cost
                            shopping_cart = {}  # 清空购物车
                            msg = shop.shopping_interface(user_dic['name'], total_cost, shopping_cart)
                            print("\033[31;1m------------购买成功", msg)
                else:
                    continue
            else:
                print("空空如也")
        elif choice == 'q':
            msg = shop.shopping_interface(user_dic['name'], total_cost, shopping_cart)
            print("\033[31;1m---------",msg)
            break
        else:
            print('违规输入')
func_dic = {
    '1': login,
    '2': register,
    '3': check_balance,
    '4': transfer,
    '5': reply,
    '6': withdraw,
    '7': shopping,
}
def run():
    while True:
        print("""\033[32;1m
        1、登陆
        2、注册
        3、查看余额
        4、转账
        5、还款
        6、取款
        7、购物
        8、退出\033[0m
        """)
        choice = input("请输入功能:").strip()
        if choice == '8':
            break
        elif choice not in func_dic:
            continue
        func_dic[choice]()
# db_handler.py
import os
from conf import settings
import json
def select(name):
    path = os.path.join(settings.BASE_DB, f"{name}.json")
    if os.path.exists(path):
        with open(path, 'r', encoding='utf8')as f:
            user_info = json.load(f)
            return user_info
    else:
        return False
def save(user_info):
    path = os.path.join(settings.BASE_DB, f"{user_info['name']}.json")
    with open(path, 'w', encoding='utf8')as f:
        json.dump(user_info, f)
        f.flush()
# bank.py
from db import db_handler
def check_balance_interface(name):
    user_info = db_handler.select(name)
    balance = user_info['balance']
    return balance
def transfer_interface(user, to_user, money):
    user_info = db_handler.select(user)
    to_user_info = db_handler.select(to_user)
    if to_user_info:
        if user_info != to_user_info:
            if user_info['balance'] >= money:
                user_info['balance'] -= money
                to_user_info['balance'] += money
                user_info['bankflow'].append(f"{user} transfer to {to_user} {money}")
                to_user_info['bankflow'].append(f"{user} transfer to {to_user} {money}")
                db_handler.save(user_info)
                db_handler.save(to_user_info)
                return True, '转账成功'
            else:
                return False, '卡上余额以不足,请及时充值'
        else:
            return False, '不要给自己转'
    else:
        return False, '对方账户不存在'
def withdraw_interface(user,money):
    user_info = db_handler.select(user)
    if user_info['balance'] >= money:
        user_info['balance'] -= money
        user_info['bankflow'].append(f"{user} withdraw {money}")
        db_handler.save(user_info)
        return True, '提现成功!!!!!!'
    else:
        return False, '卡上余额以不足,请及时充值'
def reply_interface(user,reply_money):
    user_info = db_handler.select(user)
    user_info['balance'] += reply_money
    user_info['bankflow'].append(f"{user} reply {reply_money}")
    db_handler.save(user_info)
    return '还款成功!!!!!!!!'
# shop.py
from db import db_handler
def shopping_interface(name, cost, shopping_cart):
    user_info = db_handler.select(name)
    user_info['balance'] -= cost
    if cost:
        user_info['bankflow'].append(f" expense {cost}")
    if shopping_cart:
        user_info['shopping_cart'] = shopping_cart
    else:
        user_info['shopping_cart'] = {}  # 同步修改用户信息
    db_handler.save(user_info)
    return '欢迎下次光临--------'
def check_shopping_cart_interface(name):
    user_info = db_handler.select(name)
    shopping_cart = user_info['shopping_cart']
    return shopping_cart
# user.py
from db import db_handler
from lib import common
logger = common.get_logger('user')
def register_interface(name, pwd, balance=15000):
    user_info = db_handler.select(name)
    if user_info:
        logger.warning("用户已存在")
        return False, "用户已存在"
    else:
        user_info = {'name': name,
                     'password': pwd,
                     'balance': balance,
                     'bankflow': [],
                     'lock': False,
                     'shopping_cart': {}}
        db_handler.save(user_info)
        logger.info(f"{name}注册成功!!!!")
        return True, '注册成功'
def login_interface(name, pwd):
    user_info = db_handler.select(name)
    if user_info:
        if user_info['password'] == pwd and user_info['lock'] == False:
            return True, '登陆成功'
        else:
            return False, '密码错误或账户被锁定'
    else:
        return False, "用户不存在"
# common.py
import logging
import logging.config
from conf import settings
def auth(func):
    from core import src
    def wrapper(*args, **kwargs):
        if src.user_dic['name']:
            return func(*args, **kwargs)
        else:
            print("\033[31;1m请先登陆!!!\033[0m")
            src.login()
    return wrapper
def get_logger(name):
    logging.config.dictConfig(settings.LOGGING_DIC)
    logger = logging.getLogger(name)
    return logger
# start.py
import os
import sys
path = os.path.dirname(__file__)
sys.path.append(path)
from core import src
if __name__ == '__main__':
    src.run()

你或许想:《去原作者写文章的地方

「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!
0 条回复 A 作者 M 管理员
    所有的伟大,都源于一个勇敢的开始!
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论