Python实践之路6——信用卡加购物商城

一、程序需求

  模拟实现一个ATM+购物商城程序:

    1、额度15000或自定义

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

    3、可以提现,手续费5%

     4、每月22号出账单,每月10号为还款日,过期未还,按欠款总额 万分之5 每日计息

    5、支持多账户登录

    6、支持账户间转账

    7、记录每月日常消费流水

    8、提供还款接口

    9、ATM记录操作日志

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

    11、用户认证装饰器(此处不是指用户登录界面使用装饰器,而是指用户登录后,在其他功能界面执行操作前,用装饰器验证用户登录状态

二、程序代码

  1、程序框架

  2、程序说明:

  1 ## ATM信用卡购物模拟程序
  2 
  3 ### 作者介绍:
  4 
  5 * author:VisonWong
  6 
  7 ### 博客地址:
  8 
  9 * http://www.cnblogs.com/visonwong/
 10 
 11 ### 功能介绍:
 12 
 13     1、模拟实现一个ATM + 购物商城程序
 14     2、额度 15000或自定义
 15     3、实现购物商城,买东西加入 购物车,调用信用卡接口结账
 16     4、可以提现,手续费5%
 17     5、支持多账户登录
 18     6、支持账户间转账
 19     7、记录每月日常消费流水
 20     8、提供还款接口
 21     9、ATM记录操作日志
 22     10、提供管理接口,包括添加账户、修改用户额度,冻结账户等。。。
 23     11、用户认证用装饰器(此处不是指用户登录界面使用装饰器,而是指用户登录后,在其他功能界面执行操作前,用装饰器验证用户登录状态)
 24 
 25 ### 目录结构:
 26 
 27     见目录结构截图
 28 
 29 ### 运行说明:
 30 
 31 * 用户、信用卡信息数据库已经建立好
 32         ------用户:vison       登录密码:abc321     ##测试用户,对所有的用户环节进行过测试,已存在购物信息,消费记录等
 33         ------用户:vison1      登录密码:abc123     ##测试用户,对所有的用户环节进行过测试,已存在购物信息,消费记录等
 34         ------用户:vison2      登录密码:abc456     ##初始账号,暂无任何记录
 35         ------用户:vison3      登录密码:abc345     ##初始账号,暂无任何记录
 36 
 37         ------信用卡:888888    支付密码:abc1234    关联账户:vison      ##测试信用卡,对所有的信用卡环节进行过测试,已存在余额变动,账单流水等
 38         ------信用卡:666666    支付密码:abc4321    关联账户:vison1     ##测试信用卡,对所有的信用卡环节进行过测试,已存在余额变动,账单流水等
 39         ------信用卡:777777    支付密码:abc567     关联账户:vison2     ##初始信用卡账号,暂无任何记录
 40 
 41         ------管理中心用户:admin  密码:admin
 42 
 43 * 目录结构保持一致,开始启动bin目录start.py
 44 
 45 
 46 一、主程序main_core目录下mian.py中run函数开始
 47 
 48    1、把用户中心和后台管理加载到系统
 49        (1)、输入1,进入用户中心,加载authentication.user_auth()进行用户账号认证,返回用户认证状态及当前用户名
 50        (2)、输入2,进入后台管理,加载authentication.admincenter_auth()进行管理用户认证,返回用户认证状态
 51        (3)、输入q, 退出程序
 52 
 53    2、进入用户中心,认证成功后,新用户则创建购物车、购物记录和信用卡流水记录文件
 54 
 55    3、循环菜单
 56        (1)、输入1,加载shopping_welcome(account_id)函数,装饰器认证用户登录状态,调用shopping模块,进入购物商城
 57        (2)、输入2,加载account_welcome(account_id)函数,装饰器认证用户登录状态,调用accountcenter模块,进入个人中心
 58        (3)、输入3,加载credit_welcome(account_id)函数,装饰器认证用户登录状态,调用creditcard模块,进入信用卡中心
 59        (4)、输入值为b,返回上一级菜单
 60   
 61    4、菜单1:shopping商城:
 62        (1)、输入值为1,加载shopping.Shopping_mall(current_user)函数,进行商品选购,选购的商品会加入到购物车,结束购物按b返回
 63        (2)、输入值为2,加载shopping.Shopping_car(current_user)函数,查看当前用户的已购买商品及总价,按b返回,按f清空
 64        (3)、输入值为3,加载shopping.pay_shopping(current_user)函数,对购物车商品进行结算操作;
 65                         判断当前账户是否绑定信用卡,如果没绑定,需到后台管理中心绑定信用卡;
 66                         已绑定,验证支付密码及信用卡可用透支余额,支付成功后,
 67                         重写当前账户信用卡信息;
 68                         Empty_shopping_car(current_user)函数清空购物车;
 69                         accountcenter.Shoppingcar_record(current_user,list)更新用户购物记录;
 70                         creditcard.Creditcard_record(current_user,creditcard1,vlaue)更新信用卡流水记录
 71        (4)、输入值为b,返回上一级菜单
 72 
 73    5、菜单2:accountcenter个人中心:
 74        (1)、输入值1,加载accountcenter.Shopping_record(current_user)函数,查看用户购物历史记录,无购物则为空,购物记录
 75               用时间进行分割显示,按b返回;
 76        (2)、输入值2,加载accountcenter.Updata_password(current_user)函数,选择是否对密码修改,输入y,输入账号原来的密码,
 77               匹配成功,输入新的密码,再次输入新的密码,两次密码匹配成功,修改成功,否则修改失败;按b返回
 78        (3)、输入值3,加载accountcenter.Updata_address(current_user)函数,选择是否对收货地址进行修改,输入y,输入新的地址,
 79               保存默认地址为none,按b返回
 80        (4)、输入值为b,返回上一级菜单
 81 
 82    6、菜单3:creditcard信用卡中心:
 83        (1)、输入值为1,加载creditcard.My_creditcard(current_user)函数,查看当前信用卡卡号、额度、提现额度、持卡人,按b返回
 84         (2) 、输入值为2,加载creditcard.withdraw(current_user)函数,进行现金提现,提现余额统一由业务函数计算,按b返回
 85        (3)、输入值为3,加载creditcard.repay(current_user)函数,进行现金还款,还款余额统一由业务函数计算,按b返回
 86        (4)、输入值为4,加载creditcard.transfor(current_user)函数,进行用户间转账了,双方账户账户统一由业务函数计算,按b返回
 87        (5)、输入值为5,加载creditcard.check_record(current_user)函数,打印当前信用卡账户流水,按b返回
 88        (7)、输入值为b,返回上一级菜单
 89 
 90    7、进入后台管理,认证成功后:
 91        (1)、输入值为1,加载admincenter.User_create()函数,打印当前已有账号,开始进行系统账号创建,询问是否进程新用户创建;
 92               选择y,开始创建用户,输入要创建的用户名,输入密码,如果创建的用户不存在,新建用户创建成功;否则失败,按b返回
 93        (2)、输入值为2,加载 admincenter.Lock_user()函数,打印当前用户列表,以及当前的锁定状态;
 94               输入要锁定的用户名,对已有的账号进行锁定,
 95               高亮显示,被锁定的用户不能进行系统登录。按b返回
 96        (3)、输入值为3,加载 admincenter.Unlock_user()函数,打印当前用户列表,以及当前的锁定状态;
 97               输入要解锁的用户名,对已有的账号进行解锁,
 98               高亮显示,被锁定的用户不能进行系统登录。按b返回
 99        (4)、输入值为4,加载admincenter.Creditcard_create()函数,打印当前已有信用卡,开始进行系统信用卡发行,
100               输入要创建的信用卡卡号,输入密码,按b返回
101        (5)、输入值为7,加载admincenter.Updata_limit()函数,打印当前信用卡账户账号及持卡人,
102               输入要调整额度的信用卡卡号及调整额度,按b返回
103        (6)、输入值为b,返回上一级菜单
104 
105 ###关于信用卡额度,取现额度:
106         1、信用卡进行消费时(未取现),取现额度不会发生变化
107         2、取现额度只会在:取现、还款、转账时发生变化
108         3、每次取现扣除5%的手续费
109 
110 
111 ###关于数据储存方式:
112         将每个用户相关账户信息、信用卡信息、流水信息单独成立一个文件存在相关文件目录下,
113         避免多用户登录时,交叉修改数据,造成数据混乱。
114 
115 
116 readme

  3、程序目录:

  

  4、程序代码:

    1)bin目录下start.py

 1 #!/user/bin/env ptyhon
 2 # -*- coding:utf-8 -*-
 3 # Author: VisonWong
 4 
 5 import os
 6 import sys
 7 
 8 #程序主目录:获取到Credit_card-shoppingV1路径
 9 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
10 #将Credit_card-shoppingV1路径添加到系统路径
11 sys.path.insert(0,BASE_DIR)
12 # print(sys.path)
13 
14 from main__core import main
15 
16 
17 if __name__ == '__main__':            # 函数仅会在此文件下执行,导入其他文件不会执行
18    main.run()

    2)conf目录下setting.py

1 带拓展
setting

    3)database目录下的数据库:

    1、creditcard_dicts目录下:

          creditcards,用来存放所有信用卡信息:

1 {"888888": "vison", "666666": "vison1", "777777": "vison2"}

      vison1_creditcard,用来存放vison1信用卡详细信息:

1 {"666666": {"account_id": "vison1", "pay_word": "abc4321", "state_lock": 0, "credit_line": 11592, "credit_balance": 24685.0}}

     vison2_creditcard,用来存放vison2信用卡详细信息:

1 {"777777": {"account_id": "vison2", "pay_word": "abc567", "state_lock": 0, "credit_line": 20000, "credit_balance": 0}}

     vison_creditcard,用来存放vison信用卡详细信息:

1 {"888888": {"account_id": "vison", "pay_word": "abc1234", "state_lock": 0, "credit_line": 17187, "credit_balance": 20020.0}}

    2、creditcard_records目录下:

      vison1_creditrecord,用来存放vison1信用卡流水记录:

1 {"666666": {"2018-05-21": {"11:09:44": 599, "13:20:52": 599}, "2018-05-22": {"15:57:39": 4397}}}

     viosn_creditrecord,用来存放vison信用卡流水记录:

1 {"888888": {"2018-04-21": {"12:43:51": 599}}}

    3、shopping_cars目录下:

     vison1_shoppingcar,用来存放vison1准备购买的商品:

1 []

     viosn_shoppingcar,用来存放vison准备购买的商品:

1 [["Book", "599"]]

    4、shopping_records目录下:

     vison1_shoppingrecord,用来存放vison1的历史购物记录:

1 {"vison1": {"2018-05-21": {"11:09:44": [["Book", "599"]], "13:20:52": [["Book", "599"]]}, "2018-05-22": {"15:57:39": [["iPad", "2199"], ["X-box", "1199"], ["Bicyc", "999"]]}}}

       vison_shoppingrecord,用来存放vison的历史购物记录:

1 {"vison": {"2018-04-19": {"01:09:26": [["iPhone", "1299"], ["iWatch", "2999"]]}, "2018-04-21": {"12:20:44": [["Bicyc", "999"], ["Letv", "819"]], "12:24:04": [["Letv", "819"], ["Book", "599"]], "12:30:10": [["Bicyc", "999"], ["Book", "599"]], "12:30:56": [["X-box", "1199"], ["Book", "599"]], "12:32:16": [["Book", "599"]], "12:40:58": [["Book", "599"]], "12:43:51": [["Book", "599"]]}}}

    5、users_dicts目录下:

     users,用来存放所有账户信息及锁定状态:

1 {"vison": 0, "vison1": 0, "vison2": 0, "vison3": 0}

     viosn1_info,用来存放vison1账户的详细信息:

1 {"vison1": {"credit_card": "666666", "pass_word": "abc123", "state_lock": 0, "address": "u4e0au6d77u95f5u884cu533a"}}

       vison2_info,用来存放vison2账户的详细信息:

1 {"vison2": {"credit_card": "777777", "pass_word": "abc456", "state_lock": 0, "address": "None"}}

     vison3_info,用来存放vison3账户的详细信息:

1 {"vison3": {"credit_card": 0, "pass_word": "abc345", "state_lock": 0, "address": "None"}}

     vison_info,用来存放vison账户的详细信息:

1 {"vison": {"credit_card": "888888", "pass_word": "abc321", "state_lock": 0, "address": "u4e0au6d77u95f5u884cu533a"}}

     6、current_userdata,用来存放当前程序运行中所加载的账户信息及登录状态:

1 {"vison1": true}

    7、merchandise_list,用来存放商品价目:

1 iPhone    1299
2 iWatch    2999
3 Macpro    1999
4 iPad    2199
5 Bicyc    999
6 X-box    1199
7 Letv    819
8 Book    599

     4)log目录下logging.py

待拓展
logging

     5)main_core目录下

     主函数main.py

  1 #!/user/bin/env ptyhon
  2 # -*- coding:utf-8 -*-
  3 # Author: VisonWong
  4 
  5 import sys,os,json
  6 
  7 #程序主目录
  8 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  9 #添加环境变量
 10 sys.path.append(BASE_DIR)
 11 #导入功能函数
 12 from main__core import shopping,accountcenter,creditcard,authentication,admincenter
 13 from main__core import auth_deco
 14 
 15 '''数据库文件相对路径'''
 16 # 字符串加R防止被转义
 17 __db_userdata = BASE_DIR + r"databasecurrent_userdata"   #添加当前用户状态路径
 18 
 19 #定义购物中心、个人中心、信用卡中心和后台管理欢迎界面
 20 #购物中心、个人中心和信用卡中心验证用户登录状态
 21 @auth_deco.auth
 22 def shopping_welcome(account_id):
 23     print("33[36;1m欢迎进入购物中心33[0m".center(50, "*"),
 24           "
1 购物商场
"
 25           "2 查看购物车
"
 26           "3 购物结算
"
 27           "b 返回
")
 28 @auth_deco.auth
 29 def account_welcome(account_id):
 30     print("33[33;1m欢迎进入个人中心33[0m".center(50, "*"),
 31           "
1 购物历史记录
"
 32           "2 修改登录密码
"
 33           "3 修改收货地址
"
 34           "b 返回
")
 35 @auth_deco.auth
 36 def credit_welcome(account_id):
 37     print("33[36;1m信用卡中心33[0m".center(50, "*"),
 38           "
1 我的信用卡
"
 39           "2 提现
"
 40           "3 还款
"
 41           "4 转账
"
 42           "5 流水记录
"
 43           "b 返回
")
 44 def admin_welcome():
 45     print("33[36;1m管理中心33[0m".center(50, "*"),
 46           "
1 创建账号
"
 47           "2 锁定账号
"
 48           "3 解锁账号
"
 49           "4 发行信用卡
"
 50           "5 修改信用卡额度
"
 51           "b 返回
")
 52 
 53 #功能菜单字典
 54 shopping_menu = {
 55     '1': shopping.Shopping_mall,
 56     '2': shopping.Shopping_car,
 57     '3': shopping.pay_shopping
 58 }
 59 
 60 account_menu = {
 61     '1':accountcenter.Shopping_record,
 62     '2':accountcenter.Updata_password,
 63     '3':accountcenter.Updata_address
 64 }
 65 
 66 credit_menu = {
 67     '1':creditcard.My_creditcard,
 68     '2':creditcard.withdraw,
 69     '3':creditcard.repay,
 70     '4':creditcard.transfor,
 71     '5':creditcard.check_record
 72 }
 73 
 74 admin_menu = {
 75     '1':admincenter.User_create,
 76     '2':admincenter.Lock_user,
 77     '3':admincenter.Unlock_user,
 78     '4':admincenter.Creditcard_create,
 79     '5':admincenter.Updata_limit
 80 }
 81 
 82 
 83 #主函数
 84 def run():
 85 
 86     while True:
 87         print("33[35;1m欢迎进入信用卡购物模拟程序33[0m".center(50, "#"),
 88               "
1 用户中心
"
 89               "2 后台管理
"
 90               "q 退出程序
")
 91         choice_id = input("33[34;0m选择要进入模式的ID33[0m:")
 92         if choice_id == "1":
 93             res,account_id = authentication.user_auth() #用户登录认证,返回认证状态和用户名
 94             if res:
 95                 #如果认证成功,新用户创建购物车、购物记录和信用卡流水记录文件
 96                 shopping.mkshopping_car(account_id)
 97                 accountcenter.mkshopping_record(account_id)
 98                 creditcard.mkcredit_record(account_id)
 99 
100                 while True:
101                     print("33[35;1m欢迎进入用户中心33[0m".center(50, "#"),
102                           "
1 购物商城
"
103                           "2 个人中心
"
104                           "3 信用卡中心
"
105                           "b 返回
")
106                     choice1_id = input("33[34;0m选择要进入模式的ID33[0m:")
107 
108                     if choice1_id == "1":
109                         while True:
110                             shopping_welcome(account_id)
111                             shopping_choice = input("33[34;0m选择要进入模式的ID33[0m:")
112                             if shopping_choice in shopping_menu:
113                                 shopping_menu[shopping_choice](account_id)
114                             elif shopping_choice == "b":
115                                 break
116                             else:
117                                 print("33[31;0m输入的ID无效,请重新选择33[0m")
118 
119                     elif choice1_id == "2":
120                         while True:
121                             account_welcome(account_id)
122                             account_choice = input("33[34;0m选择要进入模式的ID33[0m:")
123                             if account_choice in account_menu:
124                                 account_menu[account_choice](account_id)
125                             elif account_choice == "b":
126                                 break
127                             else:
128                                 print("33[31;0m输入的ID无效,请重新选择33[0m")
129 
130                     elif choice1_id == "3":
131                         while True:
132                             credit_welcome(account_id)
133                             credit_choice = input("33[34;0m选择要进入模式的ID33[0m:")
134                             if credit_choice in credit_menu:
135                                 credit_menu[credit_choice](account_id)
136                             elif credit_choice == "b":
137                                 break
138                             else:
139                                 print("33[31;0m输入的ID无效,请重新选择33[0m")
140 
141                     elif choice1_id == "b":
142                         with open(__db_userdata, "r+", ) as  f_userdata:
143                             userdata = json.loads(f_userdata.read())
144                             del userdata[account_id]
145                             userdata = json.dumps(userdata)
146                             f_userdata.seek(0)
147                             f_userdata.truncate(0)
148                             f_userdata.write(userdata)
149                         break
150                     else:
151                         print("33[31;0m输入的ID无效,请重新选择33[0m")
152 
153         elif choice_id == "2":
154             res = authentication.admincenter_auth()
155             if res :
156                 while True:
157                     admin_welcome()
158                     admin_choice = input("33[34;0m选择要进入模式的ID33[0m:")
159                     if admin_choice in admin_menu:
160                         admin_menu[admin_choice]()
161                     elif admin_choice == "b":
162                         break
163                     else:
164                         print("33[31;0m输入的ID无效,请重新选择33[0m")
165 
166         elif choice_id == "q":
167             break
168         else:
169             print("33[31;0m输入的ID无效,请重新选择33[0m")

     认证登录模块authentication.py

 1 #!/user/bin/env ptyhon
 2 # -*- coding:utf-8 -*-
 3 # Author: VisonWong
 4 
 5 import json,os
 6 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 7 
 8 '''数据库文件相对路径'''
 9 # 字符串加R防止被转义
10 
11 __db_user_info = BASE_DIR + r"databaseusers_dicts"    #添加用户信息路径
12 __db_userdata = BASE_DIR + r"databasecurrent_userdata"   #添加当前用户认证状态路径
13 
14 
15 '''用户登录认证'''
16 def user_auth():
17     print("33[32;0m用户登录认证33[0m".center(40,"-"))
18     username = input("33[34;0m请输入用户名:33[0m")
19     password = input("33[34;0m请输入密码:33[0m")
20     with open('{}\users'.format(__db_user_info)) as f_users:
21         users = json.loads(f_users.read())
22         if username in users.keys() :
23             if users[username] == 0:
24                 with open('{}\{}_info'.format(__db_user_info, username), "r") as f_user_info:
25                     user_info = json.loads(f_user_info.read())
26                     if password == user_info[username]["pass_word"]:
27                         print("33[31;0m用户{}认证成功33[0m".format(username))
28                         with open(__db_userdata, "r+", ) as  f_userdata:
29                             userdata = json.loads(f_userdata.read())
30                             userdata[username]=True
31                             userdata = json.dumps(userdata)
32                             f_userdata.seek(0)
33                             f_userdata.truncate(0)
34                             f_userdata.write(userdata)
35                         return True,username
36             else:
37                 print("33[31;0m输入的用户名已被锁定 认证失败33[0m")
38                 return False,username
39         else:
40             print("33[31;0m输入的用户名不存在 认证失败33[0m")
41             return False,username
42 
43 
44 '''后台管理认证'''
45 def admincenter_auth():
46     print("33[32;0m后台管理登录认证33[0m".center(40,"-"))
47     admincenter_dict = {"admin": "admin"}
48     username = input("33[34;0m请输入管理用户名:33[0m")
49     password = input("33[34;0m请输入管理密码:33[0m")
50     if len(username.strip()) > 0:
51         if username in admincenter_dict.keys():
52             if password == admincenter_dict[username]:
53                 print("33[31;0m管理用户 %s 认证成功33[0m" % (username))
54                 return True
55             else:
56                 print("33[31;0m输入的密码不匹配 认证失败33[0m")
57                 return False
58         else:
59             print("33[31;0m输入的用户名不存在 认证失败33[0m")
60             return False
61     else:
62         print("33[31;0m输入的用户名为空 认证失败33[0m")
63         return False

        登录验证装饰器auth_deco.py

 1 #!/user/bin/env ptyhon
 2 # -*- coding:utf-8 -*-
 3 # Author: VisonWong
 4 
 5 import os,json
 6 
 7 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 8 '''数据库文件相对路径'''
 9 # 字符串加R防止被转义
10 __db_userdata = BASE_DIR + r"databasecurrent_userdata"   #添加当前用户认证状态路径
11 
12 '''定义页面登录验证装饰器'''
13 def auth(func):
14     def deco(*args,**kwargs):
15         with open(__db_userdata, "r", ) as  f_userdata:
16             userdata = json.loads(f_userdata.read())
17             username = ''.join(args)  #获取字符形式用户名
18             print(username)
19             if userdata[username]:
20                 print('33[32;0m认证通过,可进行余下操作33[0m')
21                 func(*args,**kwargs)   #run func()
22             else:
23                 print('33[31;0m认证未通过,请先登录33[0m')
24     return deco               #返回deco的内存地址,而deco已经在原有函数的基础上增加了新功能

      购物中心模块shopping.py

  1 #!/user/bin/env ptyhon
  2 # -*- coding:utf-8 -*-
  3 # Author: VisonWong
  4 
  5 import json,os
  6 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  7 from main__core import accountcenter,creditcard
  8 
  9 
 10 '''数据库文件相对路径'''
 11 # 字符串加R防止被转义
 12 __db_merchandise = BASE_DIR + r"databasemerchandise_list"   #添加商品路径
 13 __db_shopping_car = BASE_DIR + r"databaseshopping_cars"   #添加购物车路径
 14 __db_user_info = BASE_DIR + r"databaseusers_dicts"    #添加用户信息路径
 15 __db_credit_card = BASE_DIR + r"databasecreditcard_dicts" #添加信用卡路径
 16 
 17 
 18 
 19 
 20 '''创建购物车'''
 21 def mkshopping_car(current_user):
 22     '''
 23     此函数用来创建当前账户的购物车
 24     :param current_user: 当前账户名
 25     :return:
 26     '''
 27     #判断当前用户路径是否存在,如果不存在通过写文件的方式创建文件,并写入空列表
 28     if not os.path.exists('{}\database\shopping_cars\{}_shoppingcar'.format(BASE_DIR,current_user)):
 29         f_shoppingcar = open('{}\database\shopping_cars\{}_shoppingcar'.format(BASE_DIR,current_user), 'w')
 30         json.dump([],f_shoppingcar)
 31         f_shoppingcar.close()
 32 
 33 '''购物商城'''
 34 def Shopping_mall(current_user):
 35     '''
 36     此函数用来实现用户购买商品
 37     :param current_user:当前账户名
 38     :return:
 39     '''
 40     shopping_list,goods_list = [],[]    #定义购买商品列表,商城商品列表
 41     with open(__db_merchandise, "r", encoding="utf-8") as  f_merchandise:
 42         for item in f_merchandise:
 43             goods_list.append(item.strip().split())
 44     def goods_inf():
 45         print("编号			商品			价格")
 46         for index, item in enumerate(goods_list):
 47             print("{}			{}			{}".format(index, item[0], item[1]))
 48     while True:
 49             print(("33[32;0m目前商城在售的商品信息33[0m").center(40, "-"))
 50             goods_inf()#打印商品信息
 51             choice_id = input("
33[34;0m选择要购买的商品编号 【购买 ID】/【返回 b】33[0m:")
 52             if choice_id.isdigit():
 53                 choice_id = int(choice_id)
 54                 if choice_id < len(goods_list) and choice_id >=0:
 55                     pro_item = goods_list[choice_id]
 56                     print("33[31;0m商品{}加入购物车,价格{}.33[0m".format(pro_item[0],pro_item[1]))
 57                     shopping_list.append(pro_item)
 58                 else:
 59                     print("33[31;0m错误:没有相应的编号 请重新输入:33[0m")
 60             elif  choice_id == "b":
 61                 with open('{}\{}_shoppingcar'.format(__db_shopping_car,current_user), "r+") as f_shopping_car:
 62                     list = json.loads(f_shopping_car.read())
 63                     list.extend(shopping_list)  #在list后追加购买商品的列表,相当于拓展原列表
 64                     f_shopping_car.seek(0)
 65                     f_shopping_car.truncate(0)
 66                     list = json.dumps(list)
 67                     f_shopping_car.write(list)
 68                 break
 69             else:
 70                  print("33[31;0m错误:没有相应的编号 请重新输入:33[0m
")
 71 
 72 '''清空购物车'''
 73 def Empty_shopping_car(current_user):
 74     '''
 75     此函数用来清空购物车
 76     :param current_user: 当前账户名
 77     :return:
 78     '''
 79     with open('{}\{}_shoppingcar'.format(__db_shopping_car,current_user),'w') as f_shopping_car:
 80         list = json.dumps([])
 81         f_shopping_car.write(list)
 82 
 83 '''打印购物车商品并计算商品总额'''
 84 def count_shopping_car(current_user):
 85     '''
 86     此函数用来打印购物差商品并计算商品总额
 87     :param current_user:
 88     :return: sum(商品总额),list(商品信息列表)
 89     '''
 90     with open('{}\{}_shoppingcar'.format(__db_shopping_car, current_user), "r+") as f_shopping_car:
 91         list = json.loads(f_shopping_car.read())
 92         sum = 0
 93         for index, item in enumerate(list):
 94             print(index, item[0], item[1])
 95             sum += int(item[1])
 96     return sum,list
 97 
 98 '''查看购物车'''
 99 def Shopping_car(current_user):
100     '''
101     此函数用来查看购物车
102     :param current_user: 当前账户名
103     :return:
104     '''
105     while True:
106         print("33[32;0m购物车信息清单33[0m".center(40,"-"))
107         sum = count_shopping_car(current_user)
108         print("33[31;1m商品总额共计:{}元33[0m".format(sum))
109         if_buy = input("
33[34;0m选择要进行的操作 返回【b】/清空【f】33[0m:")
110         if if_buy == "b" :
111             break
112         if if_buy == "f":
113             Empty_shopping_car(current_user)
114 
115 '''购物结算'''
116 def pay_shopping(current_user):
117     '''
118     此函数用来进行购物结算
119     :param current_user: 当前账户名
120     :return:
121     '''
122     while True:
123         print("33[32;0m购物结算33[0m".center(40, "-"))
124         value,list = count_shopping_car(current_user)
125         if_pay = input("33[34;0m当前商品总额:{}是否进行支付 确定【y】/返回【b】33[0m:".format(value))
126         if if_pay == "y":
127             with open('{}\{}_info'.format(__db_user_info, current_user), "r+") as f_users_info:
128                     users_info = json.loads(f_users_info.read())
129                     creditcard1=users_info[current_user]["credit_card"]
130                     if creditcard1 == 0:
131                         print("33[31;0m账号{}未绑定信用卡,请到个人中心里绑定信用卡33[0m
".format(current_user))
132                     else:
133                         with open('{}\{}_creditcard'.format(__db_credit_card, current_user), "r+") as f_creditcard_info:
134                             creditcard_info = json.loads(f_creditcard_info.read())
135                             line = creditcard_info[creditcard1]["credit_line"]
136                             if (line-value) >=0:
137                                 pass_word = input("33[31;0m 请输入支付密码!33[0m")
138                                 print(pass_word)
139                                 if pass_word == creditcard_info[creditcard1]['pay_word']:
140                                     creditcard_info[creditcard1]["credit_line"]=line-value
141                                     dict=json.dumps(creditcard_info)
142                                     f_creditcard_info.seek(0)
143                                     f_creditcard_info.truncate(0)
144                                     f_creditcard_info.write(dict)
145                                     print("33[31;1m支付成功,当前额度{}元33[0m
".format(line-value))
146                                     Empty_shopping_car(current_user)  #清空购物车
147                                     accountcenter.Shoppingcar_record(current_user,list)  #更新用户购物记录
148                                     creditcard.Creditcard_record(current_user,creditcard1,value)  #
149                                 else:
150                                     print("33[31;1m 请检查支付密码33[0m")
151                             else:
152                                 print("33[31;0m当前信用卡额度{}元,不足支付购物款.33[0m
".format(line))
153         if if_pay == "b":
154             break

     个人中心模块accountcenter.py

  1 #!/user/bin/env ptyhon
  2 # -*- coding:utf-8 -*-
  3 # Author: VisonWong
  4 
  5 import json,os,time
  6 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  7 
  8 '''数据库文件相对路径'''
  9 # 字符串加R防止被转义
 10 __db_user_info = BASE_DIR + r"databaseusers_dicts"    #添加用户信息路径
 11 __db_shopping_record = BASE_DIR+ r"databaseshopping_records"#添加购物历史路径
 12 
 13 '''创建购物记录'''
 14 def mkshopping_record(current_user):
 15     '''
 16     此函数用来创建当前账户的购物记录
 17     :param current_user: 当前账户名
 18     :return:
 19     '''
 20     # 判断当前用户路径是否存在,如果不存在通过写文件的方式创建文件,并写入空字典
 21     if not os.path.exists('{}\database\shopping_records\{}_shoppingrecord'.format(BASE_DIR,current_user)):
 22         f_shoppingrecord = open('{}\database\shopping_records\{}_shoppingrecord'.format(BASE_DIR,current_user), 'w')
 23         json.dump({},f_shoppingrecord)
 24         f_shoppingrecord.close()
 25 
 26 '''更新购物记录'''
 27 def Shoppingcar_record(current_user,shopping_list):
 28     '''
 29     此函数用来更新购物记录
 30     :param current_user: 当前账户名
 31     :param shopping_list: 购物车里关于当前账户的商品列表
 32     :return:
 33     '''
 34     with open('{}\{}_shoppingrecord'.format(__db_shopping_record, current_user), "r+") as f_shoppingcar_record:
 35         record = json.loads(f_shoppingcar_record.read())
 36         months = time.strftime('%Y-%m-%d')
 37         times = time.strftime('%H:%M:%S')
 38         #依次判断用户名、日期是否已有记录
 39         if current_user not in record.keys():
 40             record[current_user]={months:{times:shopping_list}}
 41         else:
 42             if months not in record[current_user].keys():
 43                 record[current_user][months] = {times: shopping_list}
 44             else:
 45                 record[current_user][months][times] = shopping_list
 46         record = json.dumps(record)
 47         f_shoppingcar_record.seek(0)
 48         f_shoppingcar_record.truncate(0)
 49         f_shoppingcar_record.write(record)
 50 
 51 
 52 '''查看购物记录'''
 53 def Shopping_record(current_user):
 54     '''
 55     此函数用来查看购物记录
 56     :param current_user: 当前账户名
 57     :return:
 58     '''
 59     while True:
 60         print("33[32;0m用户{}购物记录33[0m".center(40, "-").format(current_user))
 61         with open('{}\{}_shoppingrecord'.format(__db_shopping_record, current_user), "r") as f_shoppingcar_record:
 62             record = json.loads(f_shoppingcar_record.read())
 63             if current_user not in record.keys():
 64                 print("33[31;0m用户{}还没有进行过消费33[0m".format(current_user))
 65             else:
 66                 datas = sorted(record[current_user])
 67                 for d in datas:    #建立三重循环,依次从商品、时刻、日期打印购物记录
 68                     times = sorted(record[current_user][d])
 69                     for t in times:
 70                         print("33[31;0m【时间】 {} {}33[0m".format(d, t))
 71                         items =record[current_user][d][t]
 72                         print("33[31;0m【商品】		【价格】33[0m")
 73                         for v in items:
 74                             print("33[31;0m {}		{}33[0m".format(v[0],v[1]))
 75             if_back = input("
33[34;0m是否返回 返回【b】33[0m:")
 76             if if_back == "b":
 77                 break
 78 
 79 '''修改登录密码'''
 80 def Updata_password(current_user):
 81     '''
 82     此函数用来修改密码
 83     :param current_user: 当前账户名
 84     :return:
 85     '''
 86     while True:
 87         print("33[32;0m修改登录密码33[0m".center(40, "-"))
 88         if_updata = input("33[34;0m是否要修改{}登录密码 确定【y】/返回【b】33[0m:".format(current_user))
 89         if if_updata == "y":
 90             with open('{}\{}_info'.format(__db_user_info, current_user), "r+") as f_user_info:
 91                 user_info = json.loads(f_user_info.read())
 92                 password = user_info[current_user]["pass_word"]
 93                 old_pwd = input("33[34;0m输入原来的密码33[0m:")
 94                 if old_pwd == password:
 95                     new_pwd = input("33[34;0m输入新的密码33[0m:")
 96                     agin_pwd = input("33[34;0m再输入新的密码33[0m:")
 97                     if new_pwd == agin_pwd:
 98                         user_info[current_user]["pass_word"]=new_pwd
 99                         user_info= json.dumps(user_info)
100                         f_user_info.seek(0)
101                         f_user_info.truncate(0)
102                         f_user_info.write(user_info)
103                         print("33[31;1m密码修改成功33[0m")
104                     else:
105                         print("33[31;0m两次密码不一致33[0m")
106                 else:
107                     print("33[31;0m密码不正确33[0m")
108         if if_updata == "b":
109             break
110 
111 '''修改收货地址'''
112 def Updata_address(current_user):
113     while True:
114         print("33[32;0m修改收货地址33[0m".center(40, "-"))
115         with open('{}\{}_info'.format(__db_user_info, current_user), "r+") as f_user_info:
116             user_info = json.loads(f_user_info.read())
117             address = user_info[current_user]["address"]
118             print("当前收货地址:		{}" .format(address))
119             if_updata = input("33[34;0m是否要修改收货地址 确定【y】/返回【b】33[0m:")
120             if if_updata == "y":
121                 new_address = input("33[34;0m输入新的收货地址33[0m:")
122                 user_info[current_user]["address"]=new_address
123                 user_info = json.dumps(user_info)
124                 f_user_info.seek(0)
125                 f_user_info.truncate(0)
126                 f_user_info.write(user_info)
127                 print("33[31;1m收货地址修改成功33[0m")
128             if if_updata == "b":
129                 break

     信用卡中心模块creditcard.py

  1 #!/user/bin/env ptyhon
  2 # -*- coding:utf-8 -*-
  3 # Author: VisonWong
  4 
  5 import json,os,time
  6 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  7 
  8 '''数据库文件相对路径'''
  9 # 字符串加R防止被转义
 10 __db_credit_card = BASE_DIR + r"databasecreditcard_dicts" #添加信用卡路径
 11 __db_user_info = BASE_DIR + r"databaseusers_dicts"    #添加用户信息路径
 12 __db_credit_record = BASE_DIR + r"databasecreditcard_records"    #添加信用卡流水路径
 13 
 14 '''定义业务类型'''
 15 TRANSACTION_TYPE = {
 16     'repay':{'action':'plus', 'interest':0},
 17     'withdraw':{'action':'minus', 'interest':0.05},
 18     'transfor':{'action':'minus', 'interest':0.05},
 19 }
 20 
 21 '''创建购物记录'''
 22 def mkcredit_record(current_user):
 23     '''
 24     此函数用来创建当前账户的购物记录
 25     :param current_user: 当前账户名
 26     :return:
 27     '''
 28     # 判断当前用户路径是否存在,如果不存在通过写文件的方式创建文件,并写入空字典
 29     if not os.path.exists('{}\database\creditcard_records\{}_creditrecord'.format(BASE_DIR,current_user)):
 30         f_creditrecord = open('{}\database\creditcard_records\{}_creditrecord'.format(BASE_DIR,current_user), 'w')
 31         json.dump({},f_creditrecord)
 32         f_creditrecord.close()
 33 
 34 
 35 '''我的信用卡'''
 36 def My_creditcard(current_user):
 37     '''
 38     此函数用来展示信用卡信息
 39     :param current_user:  当前账户名
 40     :return:
 41     '''
 42     while True:
 43         print("33[32;0m我的信用卡信息33[0m".center(40, "-"))
 44         with open('{}\{}_creditcard'.format(__db_credit_card, current_user), "r+") as f_creditcard_info, 
 45                 open('{}\{}_info'.format(__db_user_info, current_user), "r") as f_user_info:
 46             user_info = json.loads(f_user_info.read())
 47             creditcard = user_info[current_user]["credit_card"]
 48             creditcard_info = json.loads(f_creditcard_info.read())
 49             print("卡号:		{}
消费额度:		{}
提现额度:		{}
持卡人:		{}
".
 50                   format(creditcard,creditcard_info[creditcard]['credit_line'],
 51                          creditcard_info[creditcard]['credit_balance'],
 52                          creditcard_info[creditcard]['account_id']))
 53 
 54             if_back = input("33[34;0m是否退出 返回【b】33[0m:")
 55             if if_back == "b":
 56                 break
 57 
 58 
 59 '''更新信用卡流水记录'''
 60 def Creditcard_record(current_user,creditcard,value):
 61     '''
 62     此函数用来更新信用卡流水记录
 63     :param current_user:  当前账户名
 64     :param creditcard:    账户信用卡号
 65     :param value:         消费金额
 66     :return:
 67     '''
 68     with open('{}\{}_creditrecord'.format(__db_credit_record, current_user), "r+") as f_credit_record:
 69         credit_record = json.loads(f_credit_record.read())
 70         months = time.strftime('%Y-%m-%d')
 71         times = time.strftime("%H:%M:%S")
 72         if creditcard not in credit_record.keys():
 73             credit_record[creditcard]={months:{times:value}}
 74         else:
 75             if months not in credit_record[creditcard].keys():
 76                 credit_record[creditcard][months] = {times: value}
 77             else:
 78                 credit_record[creditcard][months][times] = value
 79         credit_record = json.dumps(credit_record)
 80         f_credit_record.seek(0)
 81         f_credit_record.truncate(0)
 82         f_credit_record.write(credit_record)
 83 
 84 '''查看信用卡流水'''
 85 def check_record(current_user):
 86     while True:
 87         with open('{}\{}_info'.format(__db_user_info, current_user), "r") as f_user_info:
 88             user_info = json.loads(f_user_info.read())
 89             creditcard = user_info[current_user]["credit_card"]
 90         print("33[32;0m信用卡{}流水单33[0m".center(40, "-").format(creditcard))
 91         with open('{}\{}_creditrecord'.format(__db_credit_record, current_user), "r") as f_card_record:
 92             record = json.loads(f_card_record.read())
 93             if creditcard not in record.keys():
 94                 print("33[31;0m信用卡{}还没有进行过消费33[0m".format(creditcard))
 95             else:
 96                 datas = sorted(record[creditcard])
 97                 for d in datas:
 98                     times = sorted(record[creditcard][d])
 99                     for t in times:
100                         print("33[31;0m【时间】 {} {}33[0m".format(d, t))
101                         cost = record[creditcard][d][t]
102                         print("33[31;0m【流水】		{}33[0m".format(cost))
103             if_back = input("
33[34;0m是否返回 返回【b】33[0m:")
104             if if_back == "b":
105                 break
106 
107 
108 '''定义业务函数'''
109 def make_transaction(current_user,tran_type,amount):
110     '''
111     此函数用来计算不同业务的账户余额计算
112     :param current_user:    当前用户名
113     :param tran_type:       业务类型
114     :param amount:          业务数额
115     :return:                新的余额
116     '''
117     with open('{}\{}_creditcard'.format(__db_credit_card, current_user), "r+") as f_creditcard_info,
118         open('{}\{}_info'.format(__db_user_info, current_user), "r") as f_user_info:
119         user_info = json.loads(f_user_info.read())
120         creditcard = user_info[current_user]["credit_card"]
121         creditcard_info = json.loads(f_creditcard_info.read())
122         amount = int(amount)
123         if tran_type in  TRANSACTION_TYPE:
124             interest =  amount * TRANSACTION_TYPE[tran_type]['interest']
125             old_balance = creditcard_info[creditcard]['credit_balance']
126             if TRANSACTION_TYPE[tran_type]['action'] == 'plus':
127                 new_balance = old_balance + amount + interest
128             elif TRANSACTION_TYPE[tran_type]['action'] == 'minus':
129                 new_balance = old_balance - amount - interest
130             if  new_balance < 0:
131                 print('33[31;1m 您的信用卡余额不足,当前余额为{}.33[0m'.format(old_balance))
132             else:
133                 creditcard_info[creditcard]['credit_balance'] = new_balance
134                 creditcard_info = json.dumps(creditcard_info)
135                 f_creditcard_info.seek(0)
136                 f_creditcard_info.truncate(0)
137                 f_creditcard_info.write(creditcard_info)
138                 return new_balance
139         else:
140             print("33[31;1m 您输入的交易模式不存在!33[0m".format(tran_type))
141 
142 
143 '''还款'''
144 def repay(current_user):
145     '''
146     此函数用来实现还款功能
147     :param current_user:  当前账户名
148     :return:
149     '''
150     while True:
151         print("33[32;0m还款33[0m".center(40, "-"))
152         if_repay = input("33[34;0m是否要还款 确定【y】/返回【b】33[0m:")
153         if if_repay == 'y':
154             repay_amount = input("33[33;1m请输入还款金额.33[0m").strip()
155             if len(repay_amount) >0 and repay_amount.isdigit():
156                 new_balance = make_transaction(current_user,'repay',repay_amount)
157             if new_balance:
158                 print('33[42;1m 还款成功,当前余额为{} 33[0m'.format(new_balance))
159             else:
160                 print('33[31;1m 请检查输入金额!33[0m')
161         if if_repay == 'b':
162             break
163 
164 '''取现'''
165 def withdraw(current_user):
166     '''
167     此函数用来实现取现功能
168     :param current_user:  当前账户名
169     :return:
170     '''
171     while True:
172         print("33[32;0m取现33[0m".center(40, "-"))
173         if_withdraw = input("33[34;0m是否要取现 确定【y】/返回【b】33[0m:")
174         if if_withdraw == 'y':
175             withdraw_amount = input("33[33;1m请输入取现金额.33[0m").strip()
176             if len(withdraw_amount) >0 and withdraw_amount.isdigit():
177                 new_balance = make_transaction(current_user,'withdraw',withdraw_amount)
178             if new_balance:
179                 print('33[42;1m 取现成功,当前余额为{} 33[0m'.format(new_balance))
180             else:
181                 print('33[31;1m 请检查输入金额!33[0m')
182         if if_withdraw == 'b':
183             break
184 
185 '''转账'''
186 def transfor(current_user):
187     '''
188     此函数用来实现转账功能
189     :param current_user:  当前账户名
190     :return:
191     '''
192     while True:
193         print("33[32;0m转账33[0m".center(40, "-"))
194         if_transfor = input("33[34;0m是否要转账 确定【y】/返回【b】33[0m:")
195         if if_transfor == 'y':
196             current_user1 = input("33[33;1m请输入转账账户.33[0m").strip()
197             transfor_amount = input("33[33;1m请输入转账金额.33[0m").strip()
198             if len(transfor_amount) >0 and transfor_amount.isdigit():
199                 new_balance = make_transaction(current_user,'transfor',transfor_amount)
200                 new_balance1 = make_transaction(current_user1,'repay',transfor_amount)
201             if new_balance:
202                 print('33[42;1m 转账成功,当前余额为{}. 33[0m'.format(new_balance))
203             else:
204                 print('33[31;1m 请检查输入金额!33[0m')
205         if if_transfor == 'b':
206             break

     后台管理模块admincenter.py

  1 #!/user/bin/env ptyhon
  2 # -*- coding:utf-8 -*-
  3 # Author: VisonWong
  4 
  5 import os,json
  6 
  7 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  8 
  9 '''数据库文件相对路径'''
 10 __db_users_info = BASE_DIR + r"databaseusers_dicts"   #添加用户信息路径
 11 __db_creditcard_dict = BASE_DIR + r"databasecreditcard_dicts" #添加信用卡路径
 12 
 13 '''创建用户'''
 14 def User_create(address="None",locked=0,creditcard=0):
 15     while True:
 16         print("开始创建用户".center(50,"-"))
 17         with open('{}\users'.format(__db_users_info), "r+") as f_users_info:
 18             users_info = json.loads(f_users_info.read())
 19             print("系统已有用户 【{}】".format(users_info.keys()))
 20             if_create = input("
33[34;0m是否创建新的用户 确定【y】/返回【b】33[0m:")
 21             if if_create == "y":
 22                 username = input("33[34;0m输入要添加账户的用户名:33[0m")
 23                 password = input("33[34;0m输入添加账户的密码:33[0m")
 24                 if username not in users_info:
 25                     users_info[username] = 0
 26                     users_info = json.dumps(users_info)
 27                     f_users_info.seek(0)
 28                     f_users_info.truncate(0)
 29                     f_users_info.write(users_info)
 30 
 31                     f_user_info = open('{}\{}_info'.format(__db_users_info, username),'w')
 32                     json.dump({}, f_user_info)
 33 
 34                     if len(username.strip()) > 0 and len(password.strip()) > 0:
 35                         user_info = {}
 36                         user_info[username] = {"credit_card":creditcard,"pass_word":password,"state_lock":locked,"address":address,}
 37                         user_info = json.dumps(user_info)
 38                         f_user_info.seek(0)
 39                         f_user_info.truncate(0)
 40                         f_user_info.write(user_info)
 41                         f_user_info.close()
 42                         print("33[31;1m创建用户 %s 成功33[0m
"%(username))
 43                     else:
 44                         print("33[31;0m输入的用户名或密码为空33[0m
")
 45                 else:
 46                     print("33[31;0m用户名 %s 已经存在33[0m
"%(username))
 47             if if_create == "b":
 48                 break
 49 
 50 
 51 '''发行信用卡'''
 52 def Creditcard_create(limit=15000,locked=0,balance =0):
 53     while True:
 54         print("发行信用卡".center(50, "-"))
 55         with open('{}\creditcards'.format(__db_creditcard_dict), "r+") as f_creditcard_dicts:
 56             creditcards_info = json.loads(f_creditcard_dicts.read())
 57             for key in creditcards_info:
 58                 print("系统已有信用卡 【%s】 	持卡人 【%s】" % (key,creditcards_info[key]))
 59             if_create = input("
33[34;0m是否发行新的信用卡 确定【y】/返回【b】33[0m:")
 60             if if_create == "y":
 61                 creditcard = input("33[34;0m输入要发行信用卡卡号(6位数字):33[0m")
 62                 if creditcard not in creditcards_info.keys():
 63                     if creditcard.isdigit() and len(creditcard) == 6:
 64                         password = input("33[34;0m输入要发行信用卡的密码:33[0m")
 65                         if len(password.strip()) > 0:
 66                             username = input("33[34;0m输入要发行信用卡申请人:33[0m")
 67                             if len(username.strip()) > 0:
 68                                 creditcards_info[creditcard]=username
 69                                 creditcards_info = json.dumps(creditcards_info)
 70                                 f_creditcard_dicts.seek(0)
 71                                 f_creditcard_dicts.truncate(0)
 72                                 f_creditcard_dicts.write(creditcards_info)
 73 
 74                                 f_credit_info = open('{}\{}_creditcard'.format(__db_creditcard_dict, username), 'w')
 75                                 json.dump({}, f_credit_info)
 76 
 77                                 creditcard_info = {}
 78                                 creditcard_info[creditcard] = {"account_id":username, "pay_word":password,
 79                                                                "state_lock":locked,"credit_line":limit,
 80                                                                "credit_balance":balance}
 81                                 creditcard_info = json.dumps(creditcard_info)
 82                                 f_credit_info.seek(0)
 83                                 f_credit_info.truncate(0)
 84                                 f_credit_info.write(creditcard_info)
 85 
 86                                 with open('{}\{}_info'.format(__db_users_info, username), "r+") as f_user_info:
 87                                     user_info = json.loads(f_user_info.read())
 88                                     user_info[username]["credit_card"] = creditcard
 89                                     user_info = json.dumps(user_info)
 90                                     f_user_info.seek(0)
 91                                     f_user_info.truncate(0)
 92                                     f_user_info.write(user_info)
 93 
 94                                 print("33[31;0m发行信用卡 %s 成功 额度 %s33[0m
"%(creditcard,limit))
 95                             else:
 96                                 print("33[31;0m信用卡申请人不能为空33[0m
")
 97                         else:
 98                             print("33[31;0m输入的密码为空33[0m
")
 99                     else:
100                         print("33[31;0m信用卡 %s 卡号不符合规范33[0m
" % (creditcard))
101                 else:
102                     print("33[31;0m信用卡 %s 已经存在33[0m
" % (creditcard))
103             if if_create == "b":
104                 break
105 
106 '''锁定用户'''
107 def Lock_user():
108     while True:
109         print("33[32;0m锁定用户33[0m".center(50, "-"))
110         with open('{}\users'.format(__db_users_info), "r+") as f_users_info:
111             users_info = json.loads(f_users_info.read())
112             for key in users_info:
113                 if users_info[key] == 0:
114                     print("系统用户 【%s】		锁定状态:【未锁定】"%(key))
115                 else:
116                     print("系统用户 【%s】		锁定状态:33[7m【已锁定】33[0m" % (key))
117             if_lock = input("
33[34;0m是否进行用户锁定 确定【y】/返回【b】33[0m:")
118             if if_lock == "y":
119                 lock_user = input("33[34;0m输入要锁定的用户名33[0m:")
120                 if lock_user in users_info.keys():
121                     if users_info[lock_user] == 0:
122 
123                         users_info[lock_user] = 1
124                         users_info = json.dumps(users_info)
125                         f_users_info.seek(0)
126                         f_users_info.truncate(0)
127                         f_users_info.write(users_info)
128 
129                         with open('{}\{}_info'.format(__db_users_info,lock_user),"r+") as f_user_info:
130                             user_info = json.loads(f_user_info.read())
131                             user_info[lock_user]["state_lock"] = 1
132                             user_info = json.dumps(user_info)
133                             f_user_info.seek(0)
134                             f_user_info.truncate(0)
135                             f_user_info.write(user_info)
136 
137                         if os.path.exists('{}\{}_creditcard'.format(__db_creditcard_dict,lock_user)):
138                             with open('{}\{}_creditcard'.format(__db_creditcard_dict, lock_user), "r+") as f_credit_info:
139                                 credit_info = json.loads(f_credit_info.read())
140                                 key = ''.join(credit_info.keys())
141                                 credit_info[key]["state_lock"] = 1
142                                 credit_info = json.dumps(credit_info)
143                                 f_credit_info.seek(0)
144                                 f_credit_info.truncate(0)
145                                 f_credit_info.write(credit_info)
146                         print("33[31;1m用户 %s 锁定成功33[0m
" % (lock_user))
147                     else:
148                         print("33[31;0m用户 %s 锁定失败 之前已经被锁定33[0m
" % (lock_user))
149                 else:
150                     print("33[31;0m用户 %s 不存在33[0m
"%(lock_user))
151             if if_lock == "b":
152                 break
153 
154 '''解锁用户'''
155 def Unlock_user():
156     while True:
157         print("33[32;0m解锁用户33[0m".center(50, "-"))
158         with open('{}\users'.format(__db_users_info), "r+") as f_users_info:
159             users_info = json.loads(f_users_info.read())
160             for key in users_info:
161                 if users_info[key] == 0:
162                     print("系统用户 【%s】		锁定状态:【未锁定】"%(key))
163                 else:
164                     print("系统用户 【%s】		锁定状态:33[7m【已锁定】33[0m" % (key))
165             if_lock = input("
33[34;0m是否进行用户解锁 确定【y】/返回【b】33[0m:")
166             if if_lock == "y":
167                 unlock_user = input("33[34;0m输入要解锁的用户名33[0m:")
168                 if unlock_user in users_info.keys():
169                     if users_info[unlock_user] == 1:
170 
171                         users_info[unlock_user] = 0
172                         users_info = json.dumps(users_info)
173                         f_users_info.seek(0)
174                         f_users_info.truncate(0)
175                         f_users_info.write(users_info)
176 
177                         with open('{}\{}_info'.format(__db_users_info,unlock_user),"r+") as f_user_info:
178                             user_info = json.loads(f_user_info.read())
179                             user_info[unlock_user]["state_lock"] = 0
180                             user_info = json.dumps(user_info)
181                             f_user_info.seek(0)
182                             f_user_info.truncate(0)
183                             f_user_info.write(user_info)
184 
185                         if os.path.exists('{}\{}_creditcard'.format(__db_creditcard_dict,unlock_user)):
186                             with open('{}\{}_creditcard'.format(__db_creditcard_dict, unlock_user), "r+") as f_credit_info:
187                                 credit_info = json.loads(f_credit_info.read())
188                                 key = ''.join(credit_info.keys())
189                                 credit_info[key]["state_lock"] = 0
190                                 credit_info = json.dumps(credit_info)
191                                 f_credit_info.seek(0)
192                                 f_credit_info.truncate(0)
193                                 f_credit_info.write(credit_info)
194                         print("33[31;1m用户 %s 解锁成功33[0m
" % (unlock_user))
195                     else:
196                         print("33[31;0m用户 %s 解锁失败 用户未被锁定33[0m
" % (unlock_user))
197                 else:
198                     print("33[31;0m用户 %s 不存在33[0m
"%(unlock_user))
199             if if_lock == "b":
200                 break
201 
202 
203 
204 '''修改信用卡额度'''
205 def Updata_limit():
206     while True:
207         print("33[32;0m修改信用卡额度33[0m".center(70, "-"))
208         with open('{}\creditcards'.format(__db_creditcard_dict), "r+") as f_creditcard_dicts:
209             creditcards_info = json.loads(f_creditcard_dicts.read())
210             for key in creditcards_info:
211                 print("系统已有信用卡 【%s】 	持卡人 【%s】" % (key,creditcards_info[key]))
212             if_Updata = input("
33[34;0m是否进行信用卡额度调整 确定【y】/返回【b】33[0m:")
213             if if_Updata == "y":
214                 creditcard = input("33[34;0m输入要修改额度的信用卡卡号33[0m:")
215                 if creditcard in creditcards_info.keys():
216                     limit = input("33[34;0m输入额度修改后的金额(至少¥10000)33[0m:")
217                     if limit.isdigit() and int(limit)>= 10000:
218                         limit = int(limit)
219                         with open('{}\{}_creditcard'.format(__db_creditcard_dict,
220                                                              creditcards_info[creditcard]), "r+") as f_credit_info:
221                             credit_info = json.loads(f_credit_info.read())
222                             credit_info[creditcard]["credit_line"] = limit
223                             credit_info = json.dumps(credit_info)
224                             f_credit_info.seek(0)
225                             f_credit_info.truncate(0)
226                             f_credit_info.write(credit_info)
227 
228                         print("33[31;1m信用卡 %s 额度修改成功 额度 %s 33[0m
" % (creditcard,limit))
229                     else:
230                         print("33[31;0m输入金额 ¥%s 格式错误或者小于¥1000033[0m
" % (limit))
231                 else:
232                     print("33[31;0m信用卡 【%s】 不存在33[0m
" % (creditcard))
233             if if_Updata == "b":
234                 break

                                            

原文地址:https://www.cnblogs.com/visonwong/p/9064549.html