1. 程式人生 > >第14天簡單的購物商城作業的編寫

第14天簡單的購物商城作業的編寫

功能需求:

1. 使用者可以註冊,登入,登出,查詢賬戶,退出系統,購物等操作,如下圖

2. 使用者登入進去之後可以儲存狀態資訊進之後進行其他的一些操作,如購物,支付等:

3. 使用者的資訊主要以以下的格式儲存在檔案中。

"abc|123|0,qwe|456|239"

流程的分析:

當我們遇到這樣一個需求的時候,應該如何去做呢?首先,我們應該有一個系統的介面,用來展示我們系統所具有的具體功能。然後通過使用者輸入的資訊按照功能字典分別匯入到不同的函式中進行相應的處理。

# 系統的功能提示
sys_msg = '''
歡迎使用簡單的購物車系統, 請選擇:
1.註冊 | 2.登入 | 3.賬戶 | 4.充值 | 5.購物 | 6.支付 | 7.購物車 | 10.登出 | 0.退出
>>>
'''
系統功能提示,主要用來提示使用者系統具有什麼樣的功能
# 功能字典
method_dic = {
    '1': register,  # 註冊
    '2': login,      #  登入
    '3': account,  # 查詢賬戶
    '4': top_up,  # 充值
    '5': shopping,  # 購物
    '6': pay_money,  # 支付
    '7': shop_car_info,  # 購物車
    '10': logout  # 登出
}
功能字典,通過使用者的輸入呼叫不同的函式處理不同的功能
# 這個就是實現系統介面的函式,通過使用者輸入的choice來選擇使用什麼樣的函式處理相應的功能@outer
def system(): """系統""" while True: choice = input(sys_msg).strip() # 退出系統 if choice == "0": print("退出系統! ") break # 錯誤選項 if choice not in method_dic: print("功能輸入有誤,請重新輸入!") continue # 正確的選項eg: method_dic['1']() ==> register()
method_dic[choice]() # 進入簡單的購物車系統 system()

因為此購物商城只是單純的一些函式的實現,較為簡單,具體說明在代買中已經有註釋,此處不再贅述(在每一個函式前面加上了一個裝飾器,用來標識每一個函式的執行和結束。)以下為實現的原始碼

from functools import wraps
# 儲存使用者資訊的檔案路徑
file_path = "usr.info"
# 全域性變數
# 儲存當前登入成功的使用者的資訊
# user的儲存格式 {"usr":"abc", "ps": "123", "money": 0}
user = {}
# 檔案中的使用者資訊是以[使用者名稱|密碼|資產,使用者名稱|密碼|資產]構成的,
# eg:"abc|123|0,qwe|456|239"
# 將使用者資訊從檔案中讀取出來以變數的形式儲存在記憶體中,以便於後續大量的資訊互動
# user_dic的格式:
'''
{
    "abc": {"ps": "123", "money": 0},
    "qwe": {"ps": "456", "money": 239}
}
'''
user_dic = {}  # 從檔案中讀取出來的使用者資訊
# 購物車{"iPad": 3, "Mac": 1}
shop_car_dic = {}


def outer(func):
    """在執行每一個模組之前和之後加上字串提示"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("執行%s操作".center(100, "*") % func.__doc__)
        res = func(*args, **kwargs)
        print("結束%s操作".center(100, "*") % func.__doc__)
        return res
    return wrapper


def get_users():
    """調取當前記憶體中的使用者資訊"""
    # 如果記憶體中已經有使用者的資訊,直接返回
    if user_dic:
        return user_dic
    # 讀檔案,更新記憶體中的user_dic
    with open(file_path, 'r', encoding='utf-8') as f:
        data = f.read()
        # 檔案內容為空
        if not data:
            return user_dic
        # 檔案的內容為: "abc|123|0,qwe|456|239"
        data_list = data.split(",")
        for single_user_info in data_list:
            # 切片獲取到單個使用者的資訊之後更新user_dic
            single_user_info_list = single_user_info.split("|")
            usr = single_user_info_list[0]
            ps = single_user_info_list[1]
            money = int(single_user_info_list[2])
            user_dic[usr] = {"ps": ps, "money": money}
        return user_dic


@outer
def register():
    """註冊"""
    # 獲取所有使用者的資訊
    users = get_users()
    # 賬號輸入操作
    temp_info = ""
    while True:
        username = input(temp_info + "輸入賬號: \t").strip()
        # 使用者名稱格式
        if not username:
            print("使用者名稱不能為空!")
            temp_info = "請重新"
            continue
        # 使用者名稱已經存在
        if username in users:
            print("使用者名稱已經存在!")
            temp_info = "請重新"
            continue
        # 使用者名稱不存在
        break
    # 密碼輸入操作
    temp_info = ""
    while True:
        password = input(temp_info + "輸入密碼: \t").strip()
        # 密碼格式不正確
        if len(password) < 3:
            print("您輸入的密碼過短!")
            temp_info = "請重新"
            continue
        # 密碼格式正確
        break
    # 賬號和密碼都正確,可以寫入檔案中
    with open(file_path, 'a', encoding='utf-8') as f:
        # 檔案為空,寫入str = "abc|123|0"
        if not users:
            f.write("%s|%s|%d" % (username, password, 0))
        # 檔案不為空, 寫入str = ",abc|123|0"
        else:
            f.write(",%s|%s|%d" % (username, password, 0))
    # 更新註冊資訊到記憶體中
    users[username] = {"ps": password, "money": 0}
    print("賬號註冊成功")


@outer
def login():
    """登入"""
    users = get_users()
    global user
    if user:
        print("系統已經處於登陸狀態!")
        return
    # 賬號輸入操作
    temp_info = ""
    while True:
        username = input(temp_info + "輸入賬號:\t").strip()
        # 賬號不存在
        if username not in users:
            # 檔案不為空,如果為檔案為空,就會出現一直輸入的情況
            if users:
                print("您輸入的賬號不存在!")
                temp_info = "請重新"
                continue
            return
        # 賬號存在
        break
    # 密碼輸入操作
    temp_info = ""
    count = 0
    while count < 3:
        password = input(temp_info + "輸入密碼:\t").strip()
        # 密碼不匹配
        if password == users[username]['ps']:
            print("登陸成功!")
            # 更新登陸狀態資訊
            money = users[username]['money']
            # global user
            user = {"usr": username, "ps": password, "money": money}
            # user["usr"] = username
            # user['ps'] = password
            # user['money'] = money
            return
        print("輸入的密碼有誤!")
        temp_info = "請重新"
        count += 1
    # 更新user資訊


@outer
def account():
    """查詢賬戶"""
    # 使用者已經登入
    if user:
        print("賬戶:%s | 金額: %d" % (user['usr'], user['money']))
        return
    print("當前系統未登入!")


@outer
def logout():
    """登出"""
    if not user:
        print("系統未登入!")
        return
    user.clear()
    print("登出成功")


def user_dic_write_file():
    """將記憶體中使用者資訊寫入檔案中"""
    # dic ==> str的轉換
    users = get_users()
    user_info = ""
    for k, v in users.items():
        usr = k
        ps = str(v['ps'])
        money = str(v['money'])
        if not user_info:
            user_info += "|".join((usr, ps, money))
        else:
            user_info = user_info + ',' + "|".join((usr, ps, money))
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(user_info)


def update(key, value):
    """
    更新個人賬戶的金額或者密碼
    :param key: 可以輸入ps或者是money
    :param value: 需要更改的值
    :return:
    """
    # 1. 更新user = {"usr":"abc", "ps": "123", "money": 0}
    if key == "money":
        user[key] += value
    if key == "ps":
        user[key] = value
    # 2. 更新user_dic
    users = get_users()
    users[user['usr']][key] = user[key]
    # 3. 更新檔案內容
    user_dic_write_file()


@outer
def top_up():
    """充值"""
    # 系統未登入
    if not user:
        print("請先登入系統!")
        return
    # 金額輸入操作
    temp_info = ""
    while True:
        money = input(temp_info + "輸入金額: ").strip()
        # 格式是否準確
        if not money.isdigit():
            print("您輸入的金額有誤")
            temp_info = "請重新"
            continue
        money = int(money)
        break
    # 金額更新操作
    # 1.更新user
    update('money', money)
    print("充值成功")


@outer
def pay_money():
    """支付"""
    # 購物車資訊為空
    if not shop_car_dic:
        print("您的購物車為空,請先進行購物!")
        return False
    shop_total_price = sum([price_dic[key] * value  for key, value in shop_car_dic.items()])
    # 餘額不足
    if user['money'] < shop_total_price:
        print("親,餘額不足,請充值!")
        return False
    # 餘額充足,進行購買
    update("money", 0 - shop_total_price)
    shop_car_dic.clear()
    print("購買成功!")
    return True


@outer
def shopping():
    """購物"""
    # 使用者是否登入
    if not user:
        print("系統未登入!")
        return
    # 商品編號輸入操作
    temp_info = ""
    print(goods_msg)
    while True:
        shop_num = input(temp_info + "輸入商品編號:").strip()
        if shop_num == "0":
            print("退出購物!")
            break
        # 商品編號格式錯誤
        if shop_num not in goods_dic:
            print("輸入有誤!")
            temp_info = "請重新"
            continue
        shop_name = goods_dic[shop_num]
        # 購買個數輸入操作
        temp_info = ""
        while True:
            shop_count = input(temp_info + "購買的個數:").strip()
            if not shop_count.isdigit():
                print("輸入有誤!")
                temp_info = "請重新"
                continue
            shop_count = int(shop_count)
            # 商品已經在購物車內
            if shop_name in shop_car_dic:
                shop_car_dic[shop_name] += shop_count
            else:
                shop_car_dic[shop_name] = shop_count
            break
    # 列印購物車的資訊
    shop_car_info()
    # 支付
    pay_money()


@outer
def shop_car_info():
    """購物車"""
    if not shop_car_dic:
        print("您的購物車為空!請前往購物!")
        return
    print("%s的購物車資訊為:" % user['usr'])
    for key, value in shop_car_dic.items():
        print("商品:%s | 個數:%d" % (key, value))


# 功能字典
method_dic = {
    '1': register,
    '2': login,
    '3': account,
    '4': top_up,
    '5': shopping,
    '6': pay_money,
    '7': shop_car_info,
    '10': logout
}
# 商品字典
goods_dic = {
    "1": "iPhone",
    "2": "Mac",
    "3": "iPad"
}
# 價格字典
price_dic = {
    "iPhone": 100,
    "Mac": 200,
    "iPad": 300
}
# 商品資訊提示
goods_msg = '''
請新增商品到購物車:
1. iPhone | 2. Mac | 3. iPad | 0.退出購物
'''

# 系統的功能提示
sys_msg = '''
歡迎使用簡單的購物車系統, 請選擇:
1.註冊 | 2.登入 | 3.賬戶 | 4.充值 | 5.購物 | 6.支付 | 7.購物車 | 10.登出 | 0.退出
>>>
'''


@outer
def system():
    """系統"""
    while True:
        choice = input(sys_msg).strip()
        # 退出系統
        if choice == "0":
            print("退出系統! ")
            break
        # 錯誤選項
        if choice not in method_dic:
            print("功能輸入有誤,請重新輸入!")
            continue
        # 正確的選項eg: method_dic['1']() ==> register()
        method_dic[choice]()


# 進入簡單的購物車系統
system()