第五周作业-模拟实现一个ATM + 购物商城程序

需求:

额度 15000或自定义

实现购物商城,买东西加入 购物车,调用信用卡接口结账

可以提现,手续费5%

支持多账户登录

支持账户间转账

记录每月日常消费流水

提供还款接口

ATM记录操作日志

提供管理接口,包括添加账户、用户额度,冻结账户等。。。

用户认证用装饰器

程序实现

1.逻辑图

2.主程序

2.1 modules文件下:

from . import creditcard_center,shopping_center,admin_center,authenticate
__init__.py
#!/usr/bin/env python
#-*- coding=utf-8 -*-
#-Author-:HuWei

import os,sys,json,time

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from modules import creditcard_center,admin_center
logger = admin_center.get_logger()

db_produ_list = BASE_DIR + r"/database/production_list"
db_shopping_cart = BASE_DIR + r"/database/shopping_cart"
shopping_record = BASE_DIR + r"/database/shopping_record"
db_user = BASE_DIR + r"/database/user"
db_credit_info = BASE_DIR + r"/database/creditcard_info"
user_log = BASE_DIR + r"/log/user_flowlog"

# 购物
def shopping_mall():
        shopping_list = []
        buy_list = []
        with open(db_produ_list, "r", encoding="utf-8") as f:
             for item in f:
                 shopping_list.append(item.strip("\n").split())
        while True:
            print("\33[35;1m商城在售商品清单\33[0m".center(40,"="))
            for index, item in enumerate(shopping_list):
                print("%d %s %s" % (index + 1, item[0], item[1]))
            choice_id = input("选择要购买的商品编号或返回'b':")
            if choice_id.isdigit():
                choice_id = int(choice_id)
                if choice_id <= len(shopping_list) and choice_id >= 0:
                    buy_item = shopping_list[(int(choice_id) - 1)]
                    print("商品[%s]加入购物车,价格[¥%s]" % (buy_item[0], buy_item[1]))
                    buy_list.append(buy_item)
                    shopping_log = ["商品",buy_item[0],"价格",buy_item[1]]
                    message = "--".join(shopping_log)
                    logger.info(message)
                else:
                   print("无效的编号,请重新输入")

            elif choice_id == "b":
                 with open(db_shopping_cart, "r+") as f1:
                      list = json.loads(f1.read())
                      list.extend(buy_list)
                      list = json.dumps(list)
                      f1.seek(0)
                      f1.truncate(0)
                      f1.write(list)
                 break

            else:
                print("无效的字符,请重新输入")

# 购物车
def shopping_cart():
    while True:
        with open(db_shopping_cart, "r+", encoding="utf-8") as f1:
             shopping_list = json.loads(f1.read())
             sum = 0
             print("购物车信息清单".center(50, "#"))
             for index,item in enumerate(shopping_list):
                 print(index,item[0],item[1])
                 sum += int(item[1])
             print("\33[31;1m商品总额共计:%s\33[0m" %sum)
             choice = input("清空购物车按‘c’或返回按‘b’  请选择:")
             if choice == "c":
                with open(db_shopping_cart, "w", encoding="utf-8") as f2:
                    list = json.dumps([])
                    f2.write(list)
             elif choice == "b":
                  break

# 购物结算
def shopping_pay(login_user):
    while True:
        with open(db_shopping_cart, "r+", encoding="utf-8") as f:
            shopping_list = json.loads(f.read())
            sum = 0
            for item in shopping_list:
                sum += int(item[1])
            choice = input("当前商品总额为:¥%s,是否进行支付,是'y',返回'b' 请选择:" %sum)
            if choice == "y":
                with open(db_user, "r+", encoding="utf-8") as f1:
                    user_dic = json.loads(f1.read())
                    if user_dic[login_user]["creditcard"] == 0:
                        print("该用户%s未绑定信用卡,请到个人中心绑定信用卡"%login_user)
                # 绑定de信用卡
                    else:
                        #creditcard_center.credit_api(login_user)
                        creditcard_center.credit_pay(sum,login_user)
                        shop_record(login_user, shopping_list)
                        break
            elif choice == "b":
                break

# 历史购物记录写入
def shop_record(login_user,shopping_list):
    with open(shopping_record, "r+") as f:
        record_dict = json.loads(f.read())
        month = time.strftime('%Y-%m-%d', time.localtime())
        times = time.strftime("%H:%M:%S")
        if str(login_user) not in record_dict.keys():
            record_dict[login_user]={month:{times:shopping_list}}
        else:
            if month not in record_dict[login_user].keys():
                record_dict[login_user][month] = {times: shopping_list}
            else:
                record_dict[login_user][month][times] = shopping_list
        dict = json.dumps(record_dict)
        f.seek(0)
        f.write(dict)


# 历史购物记录查询
def check_record(login_user):
    while True:
        with open(shopping_record, "r+") as f1:
            record_dict = json.loads(f1.read())
            if login_user not in record_dict.keys():
                print("\33[31;0m没有该用户%s购物记录\33[0m"%login_user)
            else:
                data = record_dict[login_user]
                for month in data:
                    times = record_dict[login_user][month]
                    for t in times:
                        print("\33[31;0m时间%s %s\33[0m\n" % (month,t))
                        list1 = record_dict[login_user][month][t]
                        print("\33[31;0m 商品    价格\33[0m")
                        for value in list1:
                            print("%s  %s" %(value[0], value[1]))
            choice = input("\n\33[34;0m是否返回 返回【b】\33[0m:")
            if choice == "b":
                break
shopping_center.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#-Author-:HuWei


import os,sys,json,time

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from modules import shopping_center,admin_center
logger = admin_center.get_logger()


db_user = BASE_DIR + r"/database/user"
db_credit_info = BASE_DIR + r"/database/creditcard_info"
credit_record = BASE_DIR + r"/database/creditcard_record"
user_log = BASE_DIR + r"/database/user_flowlog"


#卡信息
def creditcard_info():
    while True:
        with open(db_credit_info, "r+") as f:
            creditcard_data = json.loads(f.read())
        creditcard_num = input("请输入需要查询的信用卡卡号(6位数字):").strip()
        if creditcard_num in creditcard_data.keys():
            print("您要查询的信用卡信息如下".center(50, "#"))
            print("信用卡卡号:%s\n个人信息:%s\n可用额度:%s\n取现额度:%s\n" % (creditcard_num, creditcard_data[creditcard_num]["personalinfo"], creditcard_data[creditcard_num]["limit"],creditcard_data[creditcard_num]["limitcash"]))
            break
        else:
            print("信用卡卡号:%s 不存在"% creditcard_num)


#提现
def withdraw():
    while True:
          with open(db_credit_info, "r+") as f:
               creditcard_data = json.loads(f.read())
          creditcard_num = input("请输入需要提现的信用卡卡号(6位数字):").strip()
          if creditcard_num in creditcard_data.keys():
             password = input("请输入需要提现的信用卡密码(6位数字):").strip()
             if password == creditcard_data[creditcard_num]["password"]:
                print("可用额度: % s\n取现额度: % s\n" % (creditcard_data[creditcard_num]["limit"],int((creditcard_data[creditcard_num]["limitcash"]*0.95))))
                withdraw_money = input("请输入需要提现的金额(收取%5手续费)或返回'b':")
                withdraw_money = int(withdraw_money)
                if withdraw_money == "b":
                    break
                elif int(withdraw_money) <= creditcard_data[creditcard_num]["limitcash"]:
                    with open(db_credit_info, "r+") as f1:
                     new_limitcash = creditcard_data[creditcard_num]["limitcash"] - (withdraw_money + 0.05 * withdraw_money)
                     new_limit = creditcard_data[creditcard_num]["limit"] - (withdraw_money + 0.05 * withdraw_money)
                     print("您已经成功提现人民币:¥%s ,手续费:%s,可用额度:%s,取现额度:%s" % (withdraw_money, 0.05 * withdraw_money, new_limit, new_limitcash))
                     creditcard_data[creditcard_num]["limit"] = new_limit
                     creditcard_data[creditcard_num]["limitcash"] = int(new_limitcash)
                     data = json.dumps(creditcard_data)
                     f1.seek(0)
                     f1.write(data)
                     withdraw_log = [str(creditcard_data[creditcard_num]), "金额", str(withdraw_money), "信用卡提现成功"]
                     creditcard_record(creditcard_num, "提现%s" % withdraw_money)
                     message = "--".join(withdraw_log)
                     logger.info(message)
                     break
                elif int(withdraw_money) >= creditcard_data[creditcard_num]["limitcash"]:
                     print("已超出最大提现金额,请重试")
             else:
                 print("提现密码不正确,重新输入")
          else:
              print("系统没有此卡号,重新输入")



#转账
def transfer():
    while True:
        with open(db_credit_info, "r+") as f:
            creditcard_data = json.loads(f.read())
            creditcard_num = input("请输入信用卡卡号(6位数字):").strip()
            if creditcard_num in creditcard_data.keys():
                trans_creditcard_num = input("请输入对方的信用卡卡号:")
                if trans_creditcard_num in creditcard_data.keys():
                    transfer_money = input("请输入转账的金额:")
                    transfer_money = int(transfer_money)
                    if transfer_money <= creditcard_data[creditcard_num]["limit"]:
                        password = input("请输入您的信用卡密码(6位数字):").strip()
                        if password == creditcard_data[creditcard_num]["password"]:
                            creditcard_data[creditcard_num]["limit"] -= transfer_money
                            creditcard_data[creditcard_num]["limitcash"] = creditcard_data[creditcard_num]["limit"]//2
                            creditcard_data[trans_creditcard_num]["limit"] += transfer_money
                            creditcard_data[trans_creditcard_num]["limitcash"] = creditcard_data[trans_creditcard_num]["limit"]//2
                            print("您已成功向信用卡: % s转账: % s\n可用额度: % s\n取现额度: % s\n" % (trans_creditcard_num, transfer_money,creditcard_data[creditcard_num]["limit"],creditcard_data[creditcard_num]["limitcash"]))
                            data = json.dumps(creditcard_data)
                            f.seek(0)
                            f.write(data)
                            transfer_log = ["对方卡号",trans_creditcard_num,"金额",str(transfer_money), "信用卡转账成功"]
                            creditcard_record(creditcard_num, "转账%s" % transfer_money)
                            message = "--".join(transfer_log)
                            logger.info(message)
                            break
                        else:
                            print("您的密码不正确,重新输入")
                    else:
                        print("余额不足,重新输入")
                else:
                    print("该卡号 %s不存在,重新输入" % trans_creditcard_num)
            else:
                print("该卡号 %s不存在重新输入" %creditcard_num)


#还款
def repay():
    while True:
        with open(db_credit_info, "r+") as f:
            creditcard_data = json.loads(f.read())
        creditcard_num = input("请输入需要还款的信用卡卡号(6位数字):").strip()
        if creditcard_num in creditcard_data.keys():
            repay_money = input("请输入您的还款金额:")
            if repay_money.isdigit():
                repay_money = int(repay_money)
                password = input("请输入您信用卡的还款密码")
                if password == creditcard_data[creditcard_num]["password"]:
                    with open(db_credit_info, "r+") as f2:
                        creditcard_data[creditcard_num]["limit"] += repay_money
                        creditcard_data[creditcard_num]["limitcash"] = creditcard_data[creditcard_num]["limit"]//2
                        print("信用卡: %s已成功还款金额: %s\n新的可用额度: %s,新的取现额度: %s"%(creditcard_num,repay_money,creditcard_data[creditcard_num]["limit"],creditcard_data[creditcard_num]["limitcash"]))
                        data = json.dumps(creditcard_data)
                        f2.seek(0)
                        f2.write(data)
                        repay_log = [creditcard_data[creditcard_num]["personalinfo"],creditcard_num, "还款",str(repay_money)]
                        creditcard_record(creditcard_num, "还款%s" % repay_money)
                        message = "--".join(repay_log)
                        logger.info(message)
                        break
                else:
                   print("您的还款密码不正确,重新输入")
            else:
               print("金额为数字,重新输入")
        else:
            print("该卡号 % s不存在,重新输入" % creditcard_num)




#申请信用卡
def apply_creditcard(limit=15000,locked="true"):
        while True:
            with open(db_credit_info, "r+", encoding="utf-8") as f:
                 creditcard_dic = json.loads(f.read())
                 for key in creditcard_dic.keys():
                     print("系统已有信用卡:%s,持卡人:%s"%(key,creditcard_dic[key]["personalinfo"]))
                 choice = input("是否申请信用卡,是'y',返回'b':")
                 if choice == "y":
                     creditcard = input("请输入要申请的信用卡卡号(6位数字):").strip()
                     if creditcard not in creditcard_dic:
                         if creditcard.isdigit() and len(creditcard) ==6:
                            password = input("输入要申请的信用卡密码(6位数字):")
                            if len(password) == 6:
                                personalinfo = input("输入要申请的信用卡持卡人姓名:")
                                if personalinfo.isalpha():
                                   creditcard_dic[creditcard] = {"creditcard": creditcard, "password": password,"personalinfo": personalinfo, "limit": limit,"limitcash": limit // 2, "locked": locked}
                                   dic = json.dumps(creditcard_dic)
                                   f.seek(0)
                                   f.write(dic)
                                   print("信用卡: %s\n持卡人: %s\n可用额度: %s\n取现额度: %s\n \33[35;1m申请成功\033[0m" %(creditcard,personalinfo,limit,limit//2))
                                   apply_creditcard_log = [creditcard, personalinfo, "信用卡申请成功"]
                                   message = "--".join(apply_creditcard_log)
                                   logger.info(message)
                                else:
                                    print("无效的字符")
                            else:
                                print("规密码则不符合(长度6位)")
                         else:
                             print("卡号不符合规则(长度6位)")
                 elif choice == "b":
                      break


#信用卡绑定API
def credit_api():
    while True:
        with open(db_user, "r+", encoding="utf-8") as f,open(db_credit_info, "r+", encoding="utf-8") as f1:
            user_dic = json.loads(f.read())
            credit_dic = json.loads(f1.read())
        username = input("请输入需要绑定的信用卡用户名或返回按'b':")
        if username in user_dic.keys():
            creditcard_num = user_dic[username]["creditcard"]
            if creditcard_num == 0:
                print("当前用户%s没有绑定信用卡" % username)
                attach_creditcard = input("请输入需要绑定的信用卡卡号:")
                if username == credit_dic[attach_creditcard]["personalinfo"]:
                    attach_password = input("请输入需要绑定的信用卡密码:")
                    with open(db_user, "r+", encoding="utf-8") as f:
                        if attach_password == credit_dic[attach_creditcard]["password"]:
                            user_dic[username]["creditcard"]= attach_creditcard
                            dic = json.dumps(user_dic)
                            f.seek(0)
                            f.write(dic)
                            print("持卡人:%s\n信用卡卡号:%s\n已成功绑定" %(username,attach_creditcard))
                            attachemnt_log = [username,attach_creditcard, "信用卡绑定成功"]
                            message = "--".join(attachemnt_log)
                            logger.info(message)
                            break
                        else:
                            print("密码错误,请重新输入")
                else:
                    print("信用卡用户名不存在,请重新输入")
            else:
                print("当前用户%s有绑定信用卡" % username)
                break


#信用卡付款API
def credit_pay(sum,login_user):
    print("尊敬的信用卡绑定用户,欢迎来到信用卡结算中心".center(50, "#"))
    with open(db_credit_info, "r+", encoding="utf-8") as creditcard_payment,open(db_user, "r+", encoding="utf-8") as f:
         credit_dic = json.loads(creditcard_payment.read())
         user_dic = json.loads(f.read())
         pwd = input("请输入信用卡密码完成支付:")
         creditcard_num = str(user_dic[login_user]["creditcard"])
         limit = credit_dic[creditcard_num]["limit"]
         limitcash = credit_dic[creditcard_num]["limitcash"]
         if pwd == credit_dic[creditcard_num]["password"]:
             credit_dic[creditcard_num]["limit"] = limit - sum
             credit_dic[creditcard_num]["limitcash"] = limitcash - sum
             print("\33[31;1m信用卡:%s已成功付款: ¥%s\33[0m"% (creditcard_num,sum))
             data = json.dumps(credit_dic)
             creditcard_payment.seek(0)
             creditcard_payment.write(data)
             shopping_log = [login_user,creditcard_num,"信用卡结账",str(sum)]
             creditcard_record(creditcard_num,"购物支付%s"%sum)
             message = "--".join(shopping_log)
             logger.info(message)
         else:
            print("支付密码不对,请重新输入")

#信用卡流水创建
def creditcard_record(creditcard_num,record):
    with open(credit_record, "r+") as f1:
        record_dict = json.loads(f1.read())
        month = time.strftime('%Y-%m-%d', time.localtime())
        times = time.strftime("%H:%M:%S")
        if str(creditcard_num) not in record_dict.keys():
            record_dict[creditcard_num]={month:{times:record}}
        else:
            if month not in record_dict[creditcard_num].keys():
                record_dict[creditcard_num][month] = {times: record}
            else:
                record_dict[creditcard_num][month][times] = record
        dict = json.dumps(record_dict)
        f1.seek(0)
        f1.write(dict)

#信用卡流水查询
def credit_check(creditcard_num):
    while True:
        print("\33[32;0m信用卡流水单\33[0m".center(40, "-"))
        with open(credit_record, "r+") as f1:
            record_dict = json.loads(f1.read())
            print("\33[34;0m流水单日期\33[0m:")
            if creditcard_num in record_dict.keys():
                for key in record_dict[creditcard_num]:
                    print(key)
                date = input("\n\33[34;0m流水单查询,返回'b',输入流水单的日期2017-01-01\33[0m:")
                if date == "b":break
                if date in record_dict[creditcard_num].keys():
                    keys = record_dict[creditcard_num][date]
                    print("\33[31;1m当前信用卡【%s】 交易记录-》》\33[0m"%creditcard_num)
                    for key in keys:
                        print("\33[31;1m时间:%s  %s\33[0m"%(key,record_dict[creditcard_num][date][key]))
                else:
                    print("\33[31;0m输入的日期有误\33[0m\n")
            else:
                print("\33[31;0m信用卡%s还没有进行过消费\33[0m\n"%(creditcard_num))
                break
creditcard_center.py
import os,sys,json

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
db_user = BASE_DIR + r"/database/user"
db_credit_info = BASE_DIR + r"/database/creditcard_info"
db_credit_record = BASE_DIR + r"/database/creditcard_record"
db_user_log = BASE_DIR + r"/database/user_flowlog"


# 认证装饰器
def auth(auth_type):
    def outer_wrapper(func):
        if auth_type == "user_auth":
           def wrapper():
            # 用户认证
                func()
                with open(db_user, "r") as f_user:
                     user_list = json.loads(f_user.read())
                     while True:
                        user = input("请输入用户名:").strip()
                        pwd = input("请输入密码:").strip()
                        if user and pwd:
                          for key in user_list:
                           if user == user_list[key]["username"] and pwd == user_list[key]["password"]:
                                  if user_list[user]["locked"] == "false":
                                     print("用户%s认证成功" % user)
                                     return user
                                  else:
                                     print("用户%s已经被锁定,认证失败" % user)
                           else:
                               print("用户名或密码错误,认证失败")
                        else:
                            print("用户名和密码不能为空")
           return wrapper

        elif auth_type == "creditcard_auth":
            def wrapper():
                 func()
                 with open(db_credit_info, "r") as f:
                     creditcard_data = json.loads(f.read())
                     while True:
                         credit_card = input("请输入信用卡卡号(6位数字):").strip()
                         password = input("请输入信用卡密码(6位数字): ").strip()
                         if credit_card and password:
                            for key in creditcard_data:
                                 if credit_card == creditcard_data[key]["creditcard"]:
                                     if password == creditcard_data[key]["password"]:
                                       if creditcard_data[key]["locked"] == "false":
                                          print("信用卡 %s验证成功" % (credit_card))
                                          return credit_card
                                       else:
                                          print("信用卡%s已经被冻结,请使用其他信用卡" % (credit_card))
                                 else:
                                      print("信用卡卡账号或密码输入错误")
                         else:
                             print("信用卡账号输入不能为空")
            return wrapper
        elif auth_type == "admin_auth":  # 管理员认证
            def wrapper():
                 func()
                 admin_dic = {"admin": "admin", "passwrod": "admin"}
                 while True:
                     admin_name = input("请输入管理员账号 :").strip()
                     admin_pwd = input("请输入密码 :").strip()
                     if admin_name and admin_pwd:
                        if admin_name in admin_dic and admin_pwd == admin_dic["passwrod"]:
                            print("管理员账号%s登陆成功" %admin_name)
                            return admin_name
                        else:
                            print("账号或密码错误")
                     else:
                         print("管理员账号不能为空")
            return wrapper

    return outer_wrapper


@auth(auth_type="user_auth")
def user_auth():
    print("用户登陆认证".center(40,"#"))


@auth(auth_type="creditcard_auth")
def creditcard_auth():
    print("信用卡登陆认证".center(40,"#"))

@auth(auth_type="admin_auth")
def admin_auth():
    print("管理员登陆认证".center(40,"#"))
authenticate.py
#!/usr/bin/env python
#-Author-:HuWei

import os,sys,json,logging

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
db_user = BASE_DIR + r"/database/user"
db_credit_info = BASE_DIR + r"/database/creditcard_info"
user_log = BASE_DIR + r"/log/user_flowlog"


#添加用户
def add_user(creditcard = 0,locked = "true"):
      while True:
          print("添加用户".center(50,"#"))
          with open(db_user,"r+",encoding="utf-8") as f:
               user_dic = json.loads(f.read())
               for key in user_dic:
                   print("系统已有用户%s"%key)
               choice = input("是否添加用户,是'y',返回'b':")
               if choice == "y":
                   username = input("请输入要注册的用户名:").strip()
                   if username not in user_dic:
                       if username.isalpha():
                          password = input("请输入密码:")
                          if len(password) >0:
                              user_dic[username] = {"username":username,"password":password,"creditcard":creditcard,"locked":locked}
                              dic = json.dumps(user_dic)
                              f.seek(0)
                              # f.truncate(0)
                              f.write(dic)
                              print("用户: %s 添加成功"%username)
                          else:
                              print("字符串不能为空")
                       else:
                           print("只能为字母组合")
               elif choice == "b":
                    break
#锁定用户
def lock_user():
      while True:
           print("锁定用户".center(50,"#"))
           with open(db_user,"r+",encoding="utf-8") as f:
                  user_dic = json.loads(f.read())
                  for key in user_dic:
                      if user_dic[key]["locked"] == "false":
                         print("用户 %s  未锁定" %key)
                      else:
                         print("用户 %s  已锁定" %key)
                  choice = input("是否进行锁定,是'y'或返回'b':")
                  if choice == "y":
                      loc_user = input("请输入要锁定的用户名:")
                      if loc_user in user_dic.keys():
                         if user_dic[loc_user]["locked"] == "false":
                             user_dic[loc_user]["locked"] = "true"
                             dic = json.dumps(user_dic)
                             f.seek(0)
                             f.write(dic)
                             print("用户%s 锁定成功!"%loc_user)
                         else:
                             print("用户%s 锁定失败,已经锁定!"%loc_user)
                      else:
                          print("用户%s 不存在!"%loc_user)
                  elif choice == "b":
                         break

#解锁用户
def unlock_user():
     while True:
       with open(db_user,"r+",encoding="utf-8") as f:
            user_dic = json.loads(f.read())
            for key in user_dic:
                if user_dic[key]["locked"] == "false":
                   print("用户 %s  未锁定" %key)
                else:
                   print("用户 %s  已锁定" %key)
            choice = input("是否进行解锁,是'y'或返回'b':")
            if choice == "y":
               unloc_user = input("请输入要解锁的用户名:")
               if unloc_user in user_dic.keys():
                   if user_dic[unloc_user]["locked"] == "true":
                      user_dic[unloc_user]["locked"] = "false"
                      dic = json.dumps(user_dic)
                      f.seek(0)
                      f.write(dic)
                      print("用户%s 解锁成功!"%unloc_user)
                   else:
                       print("用户%s 解锁失败, 已经解锁!"%unloc_user)
               else:
                       print("用户%s 不存在!"%unloc_user)
            elif choice == "b":
                break


#冻结信用卡
def lock_creditcard():
     while True:
           print("冻结信用卡".center(50,"#"))
           with open(db_credit_info,"r+",encoding="utf-8") as f:
                creditcard_dic = json.loads(f.read())
                for key in creditcard_dic:
                    if creditcard_dic[key]["locked"] == "false":
                       print("信用卡 %s  未冻结" %key)
                    else:
                       print("信用卡 %s  已冻结" %key)
                choice = input("是否对信用卡进行冻结操作,是'y'或返回'b':")
                if choice == "y":
                    loc_creditcard = input("请输入要冻结的信用卡卡号(6位数字)")
                    if loc_creditcard in creditcard_dic.keys() and len(loc_creditcard) == 6:
                        if creditcard_dic[loc_creditcard]["locked"] == "false":
                           creditcard_dic[loc_creditcard]["locked"] = "true"
                           dic = json.dumps(creditcard_dic)
                           f.seek(0)
                           f.write(dic)
                           print("信用卡%s 冻结成功!"%loc_creditcard)
                        else:
                           print("信用卡%s 冻结失败, 已经冻结!"%loc_creditcard)
                    else:
                        print("信用卡%s 不存在!"%loc_creditcard)
                elif choice == "b":
                      break

#解冻信用卡
def unlock_creditcard():
     while True:
           print("解冻信用卡".center(50,"#"))
           with open(db_credit_info,"r+",encoding="utf-8") as f:
              creditcard_dic = json.loads(f.read())
              for key in creditcard_dic:
                  if creditcard_dic[key]["locked"] == "false":
                     print("信用卡 %s  未冻结" %key)
                  else:
                     print("信用卡 %s  已冻结" %key)
                  choice = input("是否对信用卡进行解冻操作,是'y'或返回'b':")
                  if choice == "y":
                     unloc_creditcard = input("请输入要解冻的信用卡卡号(6位数字):")
                     if unloc_creditcard in creditcard_dic.keys() and len(unloc_creditcard) == 6:
                        if creditcard_dic[unloc_creditcard]["locked"] == "true":
                           creditcard_dic[unloc_creditcard]["locked"] = "false"
                           dic = json.dumps(creditcard_dic)
                           f.seek(0)
                           f.write(dic)
                           print("信用卡%s 解冻成功!"%unloc_creditcard)
                        else:
                           print("信用卡%s 解冻失败, 已经解冻!"%unloc_creditcard)
                     else:
                        print("信用卡%s 不存在!"%unloc_creditcard)
                  elif choice == "b":
                        break

def update_password(login_user):
     while True:
         with open(db_user, "r+", encoding="utf-8") as f:
             user_dic = json.loads(f.read())
             print("当前用户账号:% s\n当前用户密码:%s" %(login_user,user_dic[login_user]["password"]))
             choice = input("是否修改当前密码,是'y',返回按'b':")
             if choice == 'y':
                 old_pwd = input("请输入%s的原密码:" %login_user)
                 if old_pwd == user_dic[login_user]["password"]:
                     new_pwd = input("请输入%s的新密码:" % login_user)
                     user_dic[login_user]["password"] = new_pwd
                     user = json.dumps(user_dic)
                     f.seek(0)
                     f.write(user)
                     print("%s 密码修改成功!" % login_user)
                     break
                 else:
                     print("%s 原密码不正确,请重新输入!" % login_user)
             elif choice == 'b':
                  break


def get_logger():
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    fh = logging.FileHandler(user_log)
    fh.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    return logger
admin_center.py

2.2 log文件下:

默认为空
user_flowlog.txt

2.3 database文件下:

{ }
user.txt
默认为空
shopping_record.txt
默认为空
shopping_cart.txt
IPhone 8800
Mac-Pro 12388
IPad 4999
Mouse 181
Bike 800
keyboard 199
Dell-Screen 5999
Nike-Watch 999
production_list.txt
默认为空
creditcard_record.txt
{ }
creditcard_info.txt

2.4 core文件下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# -Author-:HuWei

import os,sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
db_user = BASE_DIR + r"/database/user"

from modules import admin_center,creditcard_center,shopping_center,authenticate


def option_personal(login_user):
    while True:
        option_list = ["历史购物记录", "修改登陆密码", "信用卡绑定", "返回"]
        count = 0
        for option in option_list:
            count += 1
            print(str(count) + '.' + option)
        user_choice = input(">>>:")
        if user_choice.isdecimal():
            if int(user_choice) == 1:
                 print("\33[35;1m历史购物记录\033[0m".center(40, "#"))
                 shopping_center.check_record(login_user)
                 break
            elif int(user_choice) == 2:
                 print("\33[35;1m修改登陆密码\033[0m".center(40, "#"))
                 admin_center.update_password(login_user)
            elif int(user_choice) == 3:
                 print("\33[35;1m信用卡绑定\033[0m".center(40, "#"))
                 creditcard_center.credit_api()
                 break
            elif int(user_choice) == 4:
                 print("\33[35;1m返回\033[0m".center(40, "#"))
                 break
        else:
            print("无效的字符")


def option_shopping(login_user):
    while True:
        print("\33[35;1m购物中心\033[0m".center(40, "-"))
        option_list = ["购物", "查看购物车", "购物结算", "个人中心","返回"]
        count = 0
        for option in option_list:
            count += 1
            print(str(count) + '.' + option)
        user_choice = input(">>>:")
        if user_choice.isdecimal():
            if int(user_choice) == 1:
                 print("\33[35;1m购物\033[0m".center(40, "#"))
                 shopping_center.shopping_mall()
            elif int(user_choice) == 2:
                 print("\33[35;1m查看购物车\033[0m".center(40, "#"))
                 shopping_center.shopping_cart()
            elif int(user_choice) == 3:
                 print("\33[35;1m购物结算\033[0m".center(40, "#"))
                 shopping_center.shopping_pay(login_user)
            elif int(user_choice) == 4:
                 print("\33[35;1m个人中心\033[0m".center(40, "#"))
                 option_personal(login_user)
            elif int(user_choice) == 5:
                 print("\33[35;1m返回\033[0m".center(40, "#"))
                 break
        else:

            print("无效的字符")


def option_creditcard(credit_card):
    while True:
        print("\33[35;1m信用卡中心\033[0m".center(40, "-"))
        option_list = ["信用卡信息", "提现", "转账", "还款","流水记录", "申请信用卡", "返回"]
        count = 0
        for option in option_list:
            count += 1
            print(str(count) + '.' + option)
        user_choice = input(">>>:")
        if user_choice.isdecimal():
            if int(user_choice) == 1:
                 print("\33[35;1m信用卡信息\033[0m".center(40, "#"))
                 creditcard_center.creditcard_info()
            elif int(user_choice) == 2:
                  print("\33[35;1m提现\033[0m".center(40, "#"))
                  creditcard_center.withdraw()
            elif int(user_choice) == 3:
                  print("\33[35;1m转账\033[0m".center(40, "#"))
                  creditcard_center.transfer()
            elif int(user_choice) == 4:
                  print("\33[35;1m还款\033[0m".center(40, "#"))
                  creditcard_center.repay()
            elif int(user_choice) == 5:
                  print("\33[35;1m流水记录\033[0m".center(40, "#"))
                  creditcard_center.credit_check(credit_card)
            elif int(user_choice) == 6:
                  print("\33[35;1m申请信用卡\033[0m".center(40, "#"))
                  creditcard_center.apply_creditcard(limit=15000, locked="true")
            elif int(user_choice) == 7:
                  print("\33[35;1m返回\033[0m".center(40, "#"))
                  break
    else:
        print("无效的字符")


def option_backadmin(user):
    while True:
        print("\33[35;1m后台管理\033[0m".center(40, "-"))
        option_list = ["添加账户", "锁定账户", "解锁账户", "冻结信用卡","解冻信用卡", "返回"]
        count = 0
        for option in option_list:
            count += 1
            print(str(count) + '.' + option)
        user_choice = input(">>>:")
        if user_choice.isdecimal():
            if int(user_choice) == 1:
                 print("\33[35;1m添加账户\033[0m".center(40, "#"))
                 admin_center.add_user()
            elif int(user_choice) == 2:
                 print("\33[35;1m锁定账户\033[0m".center(40, "#"))
                 admin_center.lock_user()
            elif int(user_choice) == 3:
                 print("\33[35;1m解锁账户\033[0m".center(40, "#"))
                 admin_center.unlock_user()
            elif int(user_choice) == 4:
                 print("\33[35;1m冻结信用卡\033[0m".center(40, "#"))
                 admin_center.lock_creditcard()
            elif int(user_choice) == 5:
                 print("\33[35;1m解冻信用卡\033[0m".center(40, "#"))
                 admin_center.unlock_creditcard()
            elif int(user_choice) == 6:
                 print("\33[35;1m返回\033[0m".center(40, "#"))
                 break
        else:
            print("无效的字符")


while True:
    print("\33[35;1m欢迎进入信用卡网购程序\033[0m".center(40, "="))
    option_list = ["购物中心", "信用卡中心", "后台管理", "退出"]
    count = 0
    for option in option_list:
        count += 1
        print(str(count) + '.' + option)
    user_choice = input(">>>:")
    if user_choice.isdecimal():
        if int(user_choice) == 1:
            option_shopping(authenticate.user_auth())
        elif int(user_choice) == 2:
            option_creditcard(authenticate.creditcard_auth())
        elif int(user_choice) == 3:
             option_backadmin(authenticate.admin_auth())
        elif int(user_choice) == 4:
            print("再见!")
            break
    else:
        print("无效的字符")
main.py

2.5 conf文件下:

博客地址:http://www.cnblogs.com/Mr-hu/

程序运行步骤:
=======欢迎进入信用卡网购程序==========

1:用户名(huwei/123123),    购物中心进入验证
2:信用卡号(111111/111111),信用卡中心进入验证
3:管理员(admin/admin)     后台管理进入验证

第1步:根据提示输入根据选择如果验证正确,进入,进行选择,添加删除或修改
第2步:购物中心:购物,查看购物车,购物结算 功能基本实现
      个人中心:历史购物记录,修改登录密码,信用卡绑定 功能实现
      信用卡中心:查看信用卡信息,提现,转账,还款,流水记录,申请信用卡  功能实现
      后台管理:添加用户,锁定用户,解锁用户,冻结信用卡,解冻信用卡

其中第一步验证,使用装饰器实现登陆功能,购物结算通过调用信用卡支付API实现结账、

程序目录结构

    ├── 作业_ATM+购物商城
            ├── core #入口程序目录
            │   ├── __init__.py
            │   └── main.py  #入口程序(启动程序)
            ├── conf #配置文件目录
            │   ├── __init__.py
            │   └── README.txt
            ├── modules #程序核心目录
            │   ├── __init__.py
            │   ├── admin_center.py  #管理模块
            │   ├── authenticate.py  #认证模块
            │   ├── creditcard_center.py  #信用卡模块
            │   ├── shopping_center.py  #购物模块
            ├── database #程序数据库
            │   ├── creditcard_info  #信用卡数据库
            │   ├── creditcard_record  #信用卡流水记录数据库
            │   ├── production_list  #商城产品数据库
            │   |── user  #用户数据库
            │   └── shopping_cart  #购物车数据库
            │   ├── shopping_record  #购物记录
            │   
            └── log
                ├── __init__.py
                └── user_flowlog  #用户操作日志 
readme.txt

3.程序运行

 

posted @ 2017-08-24 14:53  Mr.hu  阅读(387)  评论(1编辑  收藏  举报