ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

购物车 代码

2022-04-01 01:04:32  阅读:180  来源: 互联网

标签:username good 代码 购物车 dict user print path


import os
import json

'检查db文件是否存在 不存在就创建一个'
current_path = os.path.dirname(__file__)
db_path = os.path.join(current_path, 'db')
if not os.path.isdir(db_path):
    os.mkdir(r'db')

is_login = {
    'username': None
}


def login_auth(func_name):
    def inner(*args, **kwargs):
        if is_login.get('username'):  # 如果有登录就会返回用户名1否则0
            res = func_name(*args, **kwargs)
            return res
        else:
            print('用户未登录')
            Sign()

    return inner


def register():
    username = input('username:').strip()
    password = input('password:').strip()
    password2 = input('password2:').strip()
    if password != password2:
        print('密码不一致')
        return
    user_path = os.path.join(db_path, f'{username}.json')  # 格式化输出
    if os.path.exists(user_path):
        print('用户已存在')
        return
    user_dict = {'username': username, 'password': password, 'balance': 15000, 'shopping': {}}
    with open(user_path, 'w', encoding='utf8') as f:
        json.dump(user_dict, f, ensure_ascii=False)  # ensure_ascii 如果想要输入中文需要改变
    print(f'{username}注册成功')


def Sign():
    username = input('username:').strip()
    password = input('password:').strip()
    user_path = os.path.join(db_path, f'{username}.json')
    if not os.path.exists(user_path):
        print('用户名不存在')
    with open(user_path, 'r', encoding='utf8') as f:
        user_dict = json.load(f)
    if password == user_dict['password']:
        print('登录成功')
        is_login['username'] = username
    else:
        print('密码错误')


@login_auth
def purchase():
    good_list = [
        ['挂壁面', 3],
        ['印度飞饼', 22],
        ['极品木瓜', 666],
        ['土耳其土豆', 999],
        ['伊拉克拌面', 1000],
        ['董卓戏张飞公仔', 2000],
        ['仿真玩偶', 10000]
    ]
    temp_pur_car = {}
    while True:
        for i, j in enumerate(good_list):  # i=0 j=['挂壁面', 3]
            print("商品编号:%s  |  商品名称:%s  |   商品单价:%s" % (i, j[0], j[1]))
        choice = input('输入商品编号购买或输入y退出购买添加购物:').strip()

        if choice == 'y':
            file_path = os.path.join(db_path, '%s.json' % is_login.get('username'))
            with open(file_path, 'r', encoding='utf8') as f:
                user_dict = json.load(f)
                real_shop_car = user_dict.get('shopping')
            for name in temp_pur_car:
                if name in real_shop_car:
                    real_shop_car[name][0] += temp_pur_car[name][0]
                else:
                    real_shop_car[name] = temp_pur_car[name]
                user_dict['shopping'] = real_shop_car
            with open(file_path, 'w', encoding='utf8') as f:
                json.dump(user_dict, f, ensure_ascii=False)
            print('商品数据添加购物车成功')
            break

        if not choice.isdigit():
            print('商品编号必须是数字')
            continue
        choice = int(choice)
        if not choice in range(len(good_list)):
            print('商品编号超出了现有的范围')
            continue
        target_good_list = good_list[choice]
        target_good_name = target_good_list[0]
        target_good_price = target_good_list[1]

        target_num = input('输入购买的数量').strip()
        if target_num.isdigit():
            target_num = int(target_num)
            # 如果临时购物车存在的商品 or 第一次购买的商品
            if target_good_name not in temp_pur_car:
                temp_pur_car[target_good_name] = [target_num, target_good_price]
            else:
                temp_pur_car[target_good_name][0] += target_num
        else:
            print('商品的个数必须是纯数字')


@login_auth
def settlement():
    file_path = os.path.join(db_path, '%s.json' % is_login.get('username'))
    with open(file_path, 'r', encoding='utf8') as f:
        user_dict = json.load(f)
    shop_car = user_dict['shopping']
    total_money = 0
    for good_num, good_price in shop_car.values():
        total_money += good_num * good_price
    balance = user_dict.get('balance')
    if balance > total_money:
        balance = balance - total_money
        user_dict['balance'] = balance
        user_dict['shopping'] = {}
        with open(file_path, 'w', encoding='utf8') as f:
            json.dump(user_dict, f, ensure_ascii=False)
        print(f'结算成功 消费{total_money} 余额{balance}')
    else:
        print('余额不足')


func_dict = {'1': register, '2': Sign, '3': purchase, '4': settlement}
while True:
    print("""
    1.用户注册
    2.用户登录
    3.添加购物车
    4.结算购物车
    """)
    choice = input('输入编号:').strip()
    if choice in func_dict:
        func_name = func_dict.get(choice)
        func_name()
    else:
        print('输入正确的编号')

标签:username,good,代码,购物车,dict,user,print,path
来源: https://www.cnblogs.com/RainKz/p/16084890.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有