python_項目_ATM和購物商城的程序

1 需求html

  模擬實現一個ATM + 購物商城程序
    額度15000或自定義
    實現購物商城,買東西加入購物車,調用信用卡接口結帳
    能夠提現,手續費5%
    支持多帳戶登陸
    支持帳戶間轉帳
    記錄每個月平常消費流水
    提供還款接口
    ATM記錄操做日誌
    提供管理接口,包括添加帳戶、用戶額度,凍結帳戶等。。。
    用戶認證用裝飾器python

2 程序目錄git

 1  ├── ATM+購物商城  2             ├── core #入口程序目錄
 3             │   ├── __init__.py  4             │   └── main.py  #入口程序(啓動程序)
 5             ├── conf #配置文件目錄
 6             │   ├── __init__.py  7  │ └── README.txt  8             ├── modules #程序核心目錄
 9             │   ├── __init__.py 10             │   ├── admin_center.py  #管理模塊
11             │   ├── authenticate.py  #認證模塊
12             │   ├── creditcard_center.py  #信用卡模塊
13             │   ├── shopping_center.py  #購物模塊
14             ├── database #程序數據庫
15             │   ├── creditcard_info  #信用卡數據庫
16             │   ├── creditcard_record  #信用卡流水記錄數據庫
17             │   ├── production_list  #商城產品數據庫
18             │    |── user  #用戶數據庫
19             │   └── shopping_cart  #購物車數據庫
20             │   ├── shopping_record  #購物記錄
21 22  └── log 23                 ├── __init__.py 24                 └── user_flowlog  #用戶操做日誌 
程序目錄

3 modules目錄文件數據庫

1 from . import creditcard_center, shopping_center, admin_center, authenticate
__init__
 1 import os, sys, json, time  2 
 3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  4 sys.path.append(BASE_DIR)  5 
 6 from modules import creditcard_center, admin_center  7 logger = admin_center.get_logger()  8 
 9 db_produ_list = BASE_DIR + r'/database/production_list'
 10 db_shopping_cart = BASE_DIR + r'/database/shopping_cart'
 11 shopping_record = BASE_DIR + r'/database/shopping_record'
 12 db_user = BASE_DIR + r'/database/user'
 13 db_credit_info =  BASE_DIR + r'/database/creditcard_info'
 14 user_log =  BASE_DIR + r'/log/user_flowlog'
 15 
 16 # 購物
 17 def shopping_mall():  18     shopping_list = []  19     buy_list = []  20     with open(db_produ_list, 'r', encoding='utf-8') as f:  21         for item in f:  22             shopping_list.append(item.split('\n').split())  23     while True:  24         print('商城在售商品清單'.center(50, '-'))  25         for index, item in enumerate(shopping_list):  26             print('%d %s %s' % (index+1, item[0], item[1]))  27         choice_id = input('選擇要購買的商品編號或返回b')  28         if choice_id.isdigit():  29             choice_id = int(choice_id)  30             if choice_id <= len(shopping_list) and choice_id >= 0:  31                 buy_item = shopping_list[(int(choice_id) - 1)]  32                 print('商品[%s]加入購物車,價格[¥%s]' % (buy_item[0], buy_item[1]))  33  buy_list.append(buy_item)  34                 shopping_log = ['商品', buy_item[0], '價格', buy_item[1]]  35                 message = '--'.join(shopping_log)  36  logger.info(message)  37             else:  38                 print('無效編號,請從新輸入')  39         elif choice_id == 'b':  40             with open(db_shopping_cart, 'r+') as f1:  41                 list = json.loads(f1.read())  42  list.extend(buy_list)  43                 list = json.dumps(list)  44  f1.seek(0)  45                 f1.truncate(0)  # 截斷數據
 46  f1.write(list)  47             break
 48         else:  49             print('無效的字符,請從新輸入')  50 
 51 # 購物車
 52 def shopping_cart():  53     while True:  54         with open(db_shopping_cart, 'r+', encoding='utf-8') as f1:  55             shopping_list = json.loads(f1.read())  56             sum = 0  57             print('購物車信息清單'.center(50, '-'))  58             for index, item in enumerate(shopping_list):  59                 print(index, item[0], item[1])  60                 sum += int(item[1])  61                 print('商品總額共計:' % sum)  62                 choice = input('清空購物車c或返回按b請選擇:')  63                 if choice == 'c':  64                     with open(db_shopping_cart, 'w', encoding='utf-8') as f2:  65                         list = json.dumps([])  66  f2.write(list)  67                 elif choice == 'b':  68                     break
 69 
 70 # 購物結算
 71 def shopping_pay(login_user):  72     while True:  73         with open(db_shopping_cart, 'r+', encoding='utf-8') as f:  74             shopping_list = json.loads(f.read())  75             sum = 0  76             for item in shopping_list:  77                 sum += int(item[1])  78                 choice = input('當前商品總額爲:¥%s,是否進行支付,是y,返回b,請選擇' % sum)  79                 if choice == 'y':  80                     with open(db_user, 'r+', encoding='utf-8') as f1:  81                         user_dic = json.loads(f1.read())  82                         if user_dic[login_user]['creditcard'] == 0:  83                             print('該用戶%s未綁定信用卡,請到我的中心綁定信用卡' % login_user)  84                         # 綁定的信用卡
 85                         else:  86  creditcard_center.credit_pay(sum, login_user)  87  shop_record(login_user, shopping_list)  88                             break
 89                 elif choice == 'b':  90                     break
 91 
 92 # 歷史購物記錄寫入
 93 def shop_record(login_user,shopping_list):  94     with open(shopping_record, 'r+') as f:  95         record_dict = json.loads(f.read())  96         month = time.strftime('%Y-%m-%d', time.localtime())  97         times = time.strftime('%H:%M:%S')  98         if str(login_user) not in record_dict.keys():  99             record_dict[login_user] = {month:{times:shopping_list}} 100         else: 101             if month not in record_dict[login_user].keys(): 102                 record_dict[login_user][month] = {time: shopping_list} 103             else: 104                 record_dict[login_user][month][times] = shopping_list 105             dict = json.dumps(record_dict) 106  f.seek(0) 107  f.write(dict) 108 
109 # 歷史購物記錄查詢
110 def check_record(login_user): 111     while True: 112         with open(shopping_record, 'r+') as f1: 113             record_dict = json.loads(f1.read()) 114             if login_user not in record_dict.keys(): 115                 print('沒有該用戶%s購物記錄' % login_user) 116             else: 117                 data = record_dict[login_user] 118                 for month in data: 119                     times = record_dict[login_user][month] 120                     for t in times: 121                         print('時間%s %s' % (month, t)) 122                         list1 = record_dict[login_user][month][t] 123                         print('商品 價格') 124                         for value in list1: 125                             print('%s %s' % (value[0], value[1])) 126         choice = input('是否返回b') 127         if choice == 'b': 128             break
shopping_center
 1 import os  2 import sys  3 import json  4 import time  5 from modules import shopping_center, admin_center  6 
 7 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  8 sys.path.append(BASE_DIR)  9 
 10 logger = admin_center.get_logger()  11 
 12 db_user = BASE_DIR + r'/database/user'
 13 db_credit_info = BASE_DIR + r'/database/creditcard_info'
 14 credit_record = BASE_DIR + r'/database/credicard_record'
 15 user_log = BASE_DIR + r'/database/user_flowlog'
 16 
 17 
 18 # 卡信息
 19 def creditcard_info():  20     while True:  21         with open(db_credit_info, 'r+') as f:  22             creditcard_data = json.loads(f.read())  23         creditcard_num = input('請輸入須要查詢的信用卡卡號(6位數字)').strip()  24         if creditcard_num in creditcard_data.keys():  25             print('您要查詢的信用卡信息以下:'.center(50, '-'))  26             print('信用卡卡號:%s\n我的信息:%s\n可用額度:%s\n取現額度:%s\n' % (  27                 creditcard_num, creditcard_data[creditcard_num]['personalinfo'],  28                 creditcard_data[creditcard_num]['limit'],  29                 creditcard_data[creditcard_num]['limitcash']  30  ))  31             break
 32         else:  33             print('信用卡卡號:%s不存在' % creditcard_num)  34 
 35 
 36 # 提現
 37 def withdraw():  38     while True:  39         with open(db_credit_info, 'r+') as f:  40             creditcard_data = json.loads(f.read())  41         creditcard_num = input('請輸入須要提現的信用卡卡號(6位數字):').strip()  42         if creditcard_num in creditcard_data.keys():  43             password = input('請輸入須要提現的信用卡密碼(6位數字):').strip()  44             if password == creditcard_data[creditcard_num]['password']:  45                 print('可用額度:% s\n取現額度:% s\n' % (creditcard_data[creditcard_num]['limit'],  46                                                 int((creditcard_data[creditcard_num]["limitcash"]*0.95))  47  ))  48                 withdraw_money = input('請輸入須要提現的金額(收取%5手續費)或返回b')  49                 withdraw_money = int(withdraw_money)  50                 if withdraw_money == 'b':  51                     break
 52                 elif int(withdraw_money) <= creditcard_data[creditcard_num]['limitcash']:  53                     with open(db_credit_info, 'r') as f1:  54                         new_limitcash = creditcard_data[creditcard_num]['limitcash'] - \  55                                         (withdraw_money + 0.05 * withdraw_money)  56                         new_limit = creditcard_data[creditcard_num]['limit'] - (withdraw_money+0.05*withdraw_money)  57                         print('您已經成功提現人民幣:¥%s,手續費:%s,可用額度:%s,取現額度:%s' %
 58                               (withdraw_money, 0.05 * withdraw_money, new_limit, new_limitcash)  59  )  60                         creditcard_data[creditcard_num]['limit'] = new_limit  61                         creditcard_data[creditcard_num]['limitcash'] = int(new_limitcash)  62                         data = json.dumps(creditcard_data)  63  f1.seek(0)  64  f1.write(data)  65                         withdraw_log = [str(creditcard_data[creditcard_num]), '金額', str(withdraw_money), '提現成功']  66                         message = "--".join(withdraw_log)  67  logger.info(message)  68                         break
 69                 elif int(withdraw_money) >= creditcard_data[creditcard_num]['limitcash']:  70                     print("已經超出最大提現金額,請重試")  71             else:  72                 print('提現密碼不正確,從新輸入')  73         else:  74             print('系統沒有次卡號,從新輸入')  75 
 76 
 77 # 轉帳
 78 def transfer():  79     while True:  80         with open(db_credit_info, 'r+') as f:  81             creditcard_data = json.loads(f.read())  82             creditcard_num = input('請輸入信用卡卡號(6位數字):').strip()  83             if creditcard_num in creditcard_data.keys():  84                 trans_creditcard_num = input('請輸入對方的信用卡卡號:')  85                 if trans_creditcard_num in creditcard_data.keys():  86                     transfer_money = input('請輸入轉帳金額:')  87                     transfer_money = int(transfer_money)  88                     if transfer_money <= creditcard_data[creditcard_num]['limint']:  89                         password = input('請輸入您的信用卡密碼(6位數字):').strip()  90                         if password == creditcard_data[creditcard_num]['password']:  91                             creditcard_data[creditcard_num]['limit'] -= transfer_money  92                             creditcard_data[creditcard_num]['limitcash'] = \  93                                 creditcard_data[creditcard_num]['limit'] // 2
 94                             creditcard_data[trans_creditcard_num]['limit'] += transfer_money  95                             creditcard_data[trans_creditcard_num]['limitcash'] = \  96                                 creditcard_data[trans_creditcard_num]['limit'] // 2
 97                             print('您已成功向信用卡:%s轉帳:%s\n可用額度:%s\n取現額度:%s\n'
 98                                   % (trans_creditcard_num, transfer_money,  99                                      creditcard_data[creditcard_num]['limit'], 100                                      creditcard_data[creditcard_num]['limitcash'] 101  ) 102  ) 103                             data = json.dumps(creditcard_data) 104  f.seek(0) 105  f.write(data) 106                             transfer_log = ['對方卡號', trans_creditcard_num, '金額', 107                                             str(transfer_money), '信用卡轉帳成功'
108  ] 109                             creditcard_record(creditcard_num, '轉帳%s' % transfer_money) 110                             message = '--'.join(transfer_log) 111  logger.info(message) 112                             break
113                         else: 114                             print('您的密碼不正確,從新輸入') 115                     else: 116                         print('該卡號%s 不存在,請從新輸入' % trans_creditcard_num) 117                 else: 118                     print('該卡號%s不存在,從新輸入' % creditcard_num) 119 
120 
121 # 還款
122 def repay(): 123     while True: 124         with open(db_credit_info, 'r+') as f: 125             creditcard_data = json.loads(f.read()) 126         creditcard_num = input('請輸入須要還款的信用卡卡號(6位數字):').strip() 127         if creditcard_num in creditcard_data.keys(): 128             repay_money = input('請輸入您的還款金額:') 129             if repay_money.isdigit(): 130                 repay_money = int(repay_money) 131                 password = input('請輸入您的信用卡的還款密碼') 132                 if password == creditcard_data[creditcard_num]['password']: 133                     with open(db_credit_info, 'r+') as f2: 134                         creditcard_data[creditcard_num]['limit'] += repay_money 135                         creditcard_data[creditcard_num]['limitcash'] = creditcard_data\ 136                         [creditcard_num]['limit'] // 2
137                         print('信用卡:%s已經成功還款,金額:%s\n新的可用額度:%s,新的取現額度:%s' %
138                               (creditcard_num, repay_money, creditcard_data[creditcard_num]['limit'], 139                                creditcard_data[creditcard_num]['limitcash'] 140  ) 141  ) 142                         data = json.dumps(creditcard_data) 143  f2.seek(0) 144  f2.write(data) 145                         repay_log = [creditcard_data[creditcard_num]['personalinfo'], 146                                      creditcard_num, '還款', str(repay_money) 147  ] 148                         credit_record(creditcard_num, '還款%s' % repay_money) 149                         message = '--'.join(repay_log) 150  logger.info(message) 151                         break
152                 else: 153                     print("您的還款密碼不正確,從新輸入") 154             else: 155                 print('金額爲數字,從新輸入') 156         else: 157             print('該號%s不存在,從新輸入' % creditcard_num) 158 
159 
160 # 申請信用卡
161 def apply_creditcard(limit=15000, locked='true'): 162     while True: 163         with open(db_credit_info, 'r+', encoding='utf-8') as f: 164             creditcard_dic = json.loads(f.read()) 165             for key in creditcard_dic.keys(): 166                 print('系統已有信用卡:%s,持卡人:%s' % (key, creditcard_dic[key]['personalinfo'])) 167             choice = input('是否申請信用卡,是y否b:') 168             if choice == 'y': 169                 creditcard = input('請輸入要申請的信用卡卡號(6位數字):').strip() 170                 if creditcard not in creditcard_dic: 171                     if creditcard.isdigit() and len(creditcard) == 6: 172                         password = input('輸入要申請的信用卡密碼(6位數字):') 173                         if len(password) == 6: 174                             personalinfo = input('輸入要申請的信用卡持卡人姓名:') 175                             if personalinfo.isalpha(): 176                                 creditcard_dic[creditcard] = {'creditcard': creditcard, 177                                                               'password': password, 178                                                               'personalinfo': personalinfo, 179                                                               'limit': limit, 180                                                               'limitcash': limit // 2, 181                                                               'locked': locked 182  } 183                                 dic = json.dumps(creditcard_dic) 184  f.seek(0) 185  f.write(dic) 186                                 print('信用卡:%s\n持卡人:%s\n可用額度:%s\n取現額度:%s申請成功' %
187                                       (creditcard, personalinfo, limit, limit//2) 188  ) 189                                 apply_creditcard_log = [creditcard, personalinfo, '信用卡申請成功'] 190                                 message = '--'.join(apply_creditcard_log) 191  logger.info(message) 192                             else: 193                                 print('無效字符') 194                         else: 195                             print('密碼規則不符合') 196                     else: 197                         print('卡號不符合規則') 198             elif choice == 'b': 199                 break
200 
201 
202 # 信用卡綁定API
203 def credit_api(): 204     while True: 205         with open(db_user, 'r+', encoding='utf-8') as f, open(db_credit_info, 'r+', encoding='utf-8') as f1: 206             user_dic = json.loads(f.read()) 207             credit_dic = json.loads(f1.read()) 208         username = input('請輸入須要綁定的信用卡用戶名或返回b') 209         if username in user_dic.keys(): 210             creditcard_num = user_dic[username]['creditcard'] 211             if creditcard_num == 0: 212                 print('當前用戶%s沒有綁定信用卡' % username) 213                 attach_creditcard = input("請輸入須要綁定的信用卡卡號:") 214                 if username == credit_dic[attach_creditcard]['personalinfo']: 215                     attach_password = input('請輸入須要綁定的信用卡密碼:') 216                     with open(db_user, 'r+', encoding='utf-8') as f: 217                         if attach_password == credit_dic[attach_password]['password']: 218                             user_dic[username]['creditcard'] = attach_password 219                             dic = json.dumps(user_dic) 220  f.seek(0) 221  f.write(dic) 222                             print('持卡人:%s\n信用卡號:%s\n已成功綁定' % (username, attach_password)) 223                             attach_log = [username, attach_creditcard, '信用卡綁定成功'] 224                             message = '--'.join(attach_log) 225  logger.info(message) 226                             break
227                         else: 228                             print('密碼錯誤,請從新輸入') 229                 else: 230                     print('信用卡用戶名不存在,請從新輸入') 231             else: 232                 print('當前用戶%s有綁定信用卡' % username) 233                 break
234 
235 
236 # 信用卡付款API
237 def credit_pay(sum, login_user): 238     print('尊敬的信用卡綁定用戶,歡迎來到信用卡結算中心'.center(50, '-')) 239     with open(db_credit_info, 'r+', encoding='utf-8') as credit_payment, open(db_user, 'r+', encoding='utf-8') as f: 240         credit_dic = json.loads(credit_payment.read()) 241         user_dic = json.loads(f.read()) 242         pwd = input('請輸入信用卡密碼完成支付:') 243         creditcard_num = str(user_dic[login_user]['creditcard']) 244         limit = credit_dic[creditcard_num]['limit'] 245         limitcash = credit_dic[creditcard_num]['limitcash'] 246         if pwd == credit_dic[creditcard_num]['password']: 247             credit_dic[creditcard_num]['limit'] = limit - sum 248             credit_dic[creditcard_num]['limitcash'] = limitcash - sum 249             print('信用卡:%s已經付款成功:¥%s' % (creditcard_num, sum)) 250             data = json.dumps(credit_dic) 251  credit_payment.seek(0) 252  credit_payment.write(data) 253             shopping_log = [login_user, creditcard_num, '信用卡結帳', str(sum)] 254             credit_record(creditcard_num, '購物支付%s' % sum) 255             message = '--'.join(shopping_log) 256  logger.info(message) 257         else: 258             print('支付密碼不對,請從新輸入') 259 
260 
261 # 信用卡流水建立
262 def creditcard_record(creditcard_num, record): 263     with open(credit_record, 'r+') as f1: 264         record_dict = json.loads(f1.read()) 265         month = time.strftime('%Y-%m-%d', time.localtime()) 266         times = time.strftime('%H:%M:%S') 267         if str(creditcard_num) not in record_dict.keys(): 268             record_dict[creditcard_num] = {month: {times:record}} 269         else: 270             if month not in record_dict[creditcard_num].keys(): 271                 record_dict[creditcard_num][month]= {times: record} 272             else: 273                 record_dict[creditcard_num][month][times] = record 274         dict = json.dumps(record_dict) 275  f1.seek(0) 276  f1.write(dict) 277 
278 
279 # 信用卡流水查詢
280 def credit_check(creditcard_num): 281     while True: 282         print('信用卡流水單'.center(50, '-')) 283         with open(credit_record, 'r+') as f1: 284             record_dict = json.loads(f1.read()) 285             print('流水單日期') 286             if creditcard_num in record_dict.keys(): 287                 for key in record_dict[creditcard_num]: 288                     print(key) 289                 date = input('流水單查詢,返回b, 輸入流水單日期2018-06-03') 290                 if date == 'b': break
291                 if date in record_dict[creditcard_num].keys(): 292                     keys = record_dict[creditcard_num][date] 293                     print('當前信用卡 %s 交易記錄>>>' % creditcard_num) 294                     for key in keys: 295                         print('時間:%s %s' % (key, record_dict[creditcard_num][date][key])) 296                 else: 297                     print('輸入日期有誤') 298             else: 299                 print('信用卡%s尚未進行過消費' % creditcard_num) 300                 break
creditcard_center
 1 import os, sys, json, logging  2 
 3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  4 sys.path.append(BASE_DIR)  5 
 6 db_user = BASE_DIR + r"/database/user"  # 存放用戶信息
 7 db_credit_info = BASE_DIR + r"/database/creditcard_info"  # 存放信用卡信息
 8 user_log = BASE_DIR + r"/log/user_flowlog"  # 存放日誌信息
 9 
 10 
 11 # 添加用戶
 12 def add_user(creditcard=0, locked='true'):  13     while True:  14         print("添加用戶".center(50, '-'))  15         with open(db_user, 'r+', encoding='utf-8') as f:  # encoding爲編碼的操做,將數據按照utf-8加載到內存
 16             user_dic = json.loads(f.read())  17             for key in user_dic:  18                 print("系統已經有用戶%s" % key)  19             choice = input("是否添加用戶,是y,返回b")  20             if choice == "y":  21                 username = input('請輸入要註冊的用戶名:').strip()  # 去除輸入後的空格
 22                 if username not in user_dic:  23                     if username.isalpha():  24                         password = input("請輸入密碼:")  25                         if len(password) > 0:  26                             user_dic[username] = {'username': username, 'password': password,  27                                                   'creditcard': creditcard, 'locked': locked}  28                             dic = json.dumps(user_dic)  29  f.seek(0)  30  f.write(dic)  31                             print('用戶:%s添加成功' % username)  32                         else:  33                             print('密碼不能爲空')  34                     else:  35                         print('帳戶只能爲字母組合')  36                 else:  37                     print('該帳戶已經註冊')  38             elif choice == 'b':  39                 break
 40 
 41 
 42 # 鎖定用戶
 43 def lock_user():  44     while True:  45         print('鎖定用戶'.center(50, '-'))  46         with open(db_user, 'r+', encoding='utf-8') as f:  47             user_dic = json.loads(f.read())  48             for key in user_dic:  49                 if user_dic[key]['locked'] == 'false':  50                     print('用戶%s未鎖定' % key)  51                 else:  52                     print('用戶%s未鎖定' % key)  53             choice = input("是否進行鎖定,是y或返回b")  54             if choice == 'y':  55                 loc_user = input("請輸入要鎖定的用戶名:")  56                 if loc_user in user_dic.keys:  57                     if user_dic[loc_user]['locked'] == 'false':  58                         user_dic[loc_user]['locked'] = 'true'
 59                         dic = json.dumps(user_dic)  60  f.seek(0)  61  f.write(dic)  62                         print('用戶 %s 鎖定成功' % loc_user)  63                     else:  64                         print('用戶 %s 鎖定失敗,已經鎖定!' % loc_user)  65                 else:  66                     print('用戶 %s 不存在' % loc_user)  67             elif choice == 'b':  68                 break
 69 
 70 
 71 # 凍結信用卡
 72 def lock_creditcard():  73     while True:  74         print('凍結信用卡'.center(50, '-'))  75         with open(db_credit_info, 'r+', encoding='utf-8') as f:  76             creditcard_dic = json.loads(f.read())  77             for key in creditcard_dic:  78                 if creditcard_dic[key]['locked'] == 'false':  79                     print('信用卡 %s 未凍結' % key)  80                 else:  81                     print('信用卡 %s 已凍結' % key)  82             choice = input('是否對信用卡進行凍結操做,是y或返回b:')  83             if choice == 'y':  84                 loc_creditcard = input('請輸入要凍結的信用卡卡號(6位數字)')  85                 if loc_creditcard in creditcard_dic.keys() and len(loc_creditcard) == 6:  86                     if creditcard_dic[loc_creditcard]['locked'] == 'false':  87                         creditcard_dic[loc_creditcard]['locked'] = 'true'
 88                         dic = json.dumps(creditcard_dic)  89  f.seek(0)  90  f.write(dic)  91                         print('信用卡 %s 凍結成功' % loc_creditcard)  92                     else:  93                         print('信用卡 %s 凍結失敗,已經凍結' % loc_creditcard)  94                 else:  95                     print('信用卡 %s 不存在!' % loc_creditcard)  96             elif choice == 'b':  97                 break
 98 
 99 
100 # 解凍信用卡
101 def unlock_creditcard(): 102     while True: 103         print('解凍信用卡'.center(50, '-')) 104         with open(db_credit_info, 'r+', encoding='utf-8') as f: 105             creditcard_dic = json.loads(f.read()) 106             for key in creditcard_dic: 107                 if creditcard_dic[key]['locked'] == 'false': 108                     print('信用卡 %s 未凍結' % key) 109                 else: 110                     print('信用卡 %s 已凍結' % key) 111                 choice = input('是否對信用卡進行解凍操做,是y或返回b:') 112                 if choice == 'y': 113                     unloc_creditcard = input('請輸入要解凍的信用卡號(6位數字):') 114                     if unloc_creditcard in creditcard_dic.keys() and len(unloc_creditcard) == 6: 115                         if creditcard_dic[unloc_creditcard]['locked'] == 'true': 116                             creditcard_dic[unloc_creditcard]['locked'] = 'false'
117                             dic = json.dumps(creditcard_dic) 118  f.seek(0) 119  f.write(dic) 120                             print('信用卡 %s 解凍成功!' % unloc_creditcard) 121                         else: 122                             print('信用卡 %s 解凍失敗,已經解凍!' % unloc_creditcard) 123                     else: 124                         print('信用卡 %s 不存在' % unloc_creditcard) 125                 elif choice == 'b': 126                     break
127 
128 
129 # 更新密碼
130 def update_password(login_user): 131     while True: 132         with open(db_user, 'r+', encoding='utf-8') as f: 133             user_dic = json.loads(f.read()) 134             print('當前用戶帳戶:%s\n當前用戶密碼:%s' % (login_user, user_dic[login_user]['password'])) 135             choice = input('是否修改當前密碼,是y,返回按b:') 136             if choice == 'y': 137                 old_pwd = input('請輸入%s的原密碼:' % login_user) 138                 if old_pwd == user_dic[login_user]['password']: 139                     new_pwd = input('請輸入%s的新密碼:' % login_user) 140                     user_dic[login_user]['password'] = new_pwd 141                     user = json.dumps(user_dic) 142  f.seek(0) 143  f.write(user) 144                     print('%s密碼修改爲功' % login_user) 145                     break
146                 else: 147                     print('%s 原密碼不正確,請從新輸入!' % login_user) 148             elif choice == 'b': 149                 break
150 
151 
152 # 日誌文件
153 def get_logger(): 154     logger = logging.getLogger() 155  logger.setLevel(logging.INFO) 156 
157     fh = logging.FileHandler(user_log) 158  fh.setLevel(logging.INFO) 159     formatter = logging.Formatter('%(asctime)s - %(message)s') 160  fh.setFormatter(formatter) 161  logger.addHandler(fh) 162     return logger
admin_center
 1 import os, sys, json  2 
 3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  4 db_user = BASE_DIR + r'/database/user'
 5 db_credit_info = BASE_DIR + r'/database/creditcard_info'
 6 db_credit_record = BASE_DIR +r'/database/creditcard_record'
 7 db_user_log = BASE_DIR + r'/database/user_flowlog'
 8 
 9 
10 # 認證裝飾器
11 def auth(auth_type): 12     def outer_wrapper(func): 13         if auth_type == 'user_auth': 14             def wrapper(): 15                 #用戶認證
16  func() 17                 with open(db_user, 'r') as f_user: 18                     user_list = json.loads(f_user.read()) 19                     while True: 20                         user = input('請輸入用戶名:').strip() 21                         pwd = input('請輸入密碼:').strip() 22                         if user and pwd: 23                             for key in user_list: 24                                 if user == user_list[key]['username'] and pwd == user_list[key]['password']: 25                                     if user_list[user]['locked'] == 'false': 26                                         print('用戶%s認證成功' % user) 27                                         return user 28                                     else: 29                                         print('用戶%s已經被鎖定,認證失敗' % user) 30                                 else: 31                                     print('用戶名或密碼錯誤,認證失敗') 32                             else: 33                                 print('用戶名和密碼不能爲空') 34             return wrapper 35         elif auth_type == 'creditcard_auth': 36             def wrapper(): 37  func() 38                 with open(db_credit_info, 'r') as f: 39                     creditcard_data = json.loads(f.read()) 40                     while True: 41                         credit_card = input('請輸入信用卡號(6位數字):').strip() 42                         password = input('請輸入信用卡密碼(6位數字):').strip() 43                         if credit_card and password: 44                             for key in creditcard_data: 45                                 if credit_card == creditcard_data[key]['creditcard']: 46                                     if password == creditcard_data[key]['password']: 47                                         if creditcard_data[key]['locked'] == 'false': 48                                             print('信用卡%s驗證成功' % credit_card) 49                                             return credit_card 50                                         else: 51                                             print('信用卡%s已經被凍結,請使用其它信用卡' % credit_card) 52                                     else: 53                                         print('信用卡卡號或密碼輸入錯誤') 54                         else: 55                             print('信用卡帳號輸入不能爲空') 56             return wrapper 57         elif auth_type == 'admin_auth':  # 管理員認證
58             def wrapper(): 59  func() 60                 admin_dic = {'admin': 'admin', 'password': 'admin'} 61                 while True: 62                     admin_name = input('請輸入管理員帳號:').strip() 63                     admin_pwd = input('請輸入密碼:').strip() 64                     if admin_name and admin_pwd: 65                         if admin_name in admin_dic and admin_pwd == admin_dic['password']: 66                             print('管理員帳號%s登錄成功' % admin_name) 67                             return admin_name 68                         else: 69                             print('帳號或密碼錯誤') 70                     else: 71                         print('管理員帳號不能爲空') 72             return wrapper 73     return outer_wrapper 74 
75 
76 @auth(auth_type='user_auth') 77 def user_auth(): 78     print('用戶登陸認證'.center(50, '-')) 79 
80 
81 @auth(auth_type='creditcard_auth') 82 def creditcard_auth(): 83     print('信用卡登陸認證'.center(50, '-')) 84 
85 
86 @auth(auth_type='admin_auth') 87 def admin_auth(): 88     print('管理員登陸認證'.center(50, '-'))
authenticate

4 core目錄中的文件編程

 1 import os, sys  2 
 3 # 獲取程序的主目錄
 4 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  5 # 將主目錄添加到環境變量
 6 sys.path.append(BASE_DIR)  7 from modules import admin_center, creditcard_center, shopping_center, authenticate  8 
 9 
 10 db_user = BASE_DIR + r'/database/user'
 11 
 12 
 13 def option_personal(login_user):  14     while True:  15         option_list = ['歷史購物記錄', '修改登陸密碼', '信用卡綁定', '返回']  16         count = 0  17         for option in option_list:  18             count += 1
 19             print(str(count) + '.' + option)  20         user_choice = input('>>>:')  21         if user_choice.isdecimal():  22             if int(user_choice) == 1:  23                 print('歷史購物記錄'.center(50, '-'))  24  shopping_center.check_record(login_user)  25                 break
 26             elif int(user_choice) == 2:  27                 print('修改登陸密碼'.center(50, '-'))  28  admin_center.update_password(login_user)  29             elif int(user_choice) == 3:  30                 print('信用卡綁定'.center(50, '-'))  31  creditcard_center.credit_api()  32                 break
 33             elif int(user_choice) == 4:  34                 print('返回'.center(40, '-'))  35         else:  36             print('無效的字符')  37 
 38 
 39 # 購物
 40 def option_shopping(login_user):  41     while True:  42         print('購物中心'.center(40, '-'))  43         option_list = ["購物", "查看購物車", "購物結算", "我的中心", "返回"]  44         count = 0  45         for option in option_list:  46             count += 1
 47             print(str(count) + '.' + option)  48         user_choice = input('>>>:')  49         if user_choice.isdecimal():  50             if int(user_choice) == 1:  51                 print('購物'.center(50, '-'))  52  shopping_center.shopping_mall()  53             elif int(user_choice) == 2:  54                 print('查看購物車'.center(50, '-'))  55  shopping_center.shopping_cart()  56             elif int(user_choice) == 3:  57                 print('購物結算'.center(50, '-'))  58  shopping_center.shopping_pay(login_user)  59             elif int(user_choice) == 4:  60                 print('我的中心'.center(50, '-'))  61  option_personal(login_user)  62             elif int(user_choice) == 5:  63                 print('返回'.center(50, '-'))  64                 break
 65         else:  66             print('無效字符')  67 
 68 
 69 # 信用卡
 70 def option_creditcard(credit_card):  71     while True:  72         print('信用卡中心'.center(50, '-'))  73         option_list = ["信用卡信息", "提現", "轉帳", "還款","流水記錄", "申請信用卡", "返回"]  74         count = 0  75         for option in option_list:  76             count += 1
 77             print(str(count) + '.' + option)  78         user_choice =  input('>>>:')  79         if user_choice.isdecimal():  80             if int(user_choice) == 1:  81                 print("信用卡信息".center(50, "-"))  82  creditcard_center.creditcard_info()  83             elif int(user_choice) == 2:  84                 print("提現".center(50, "-"))  85  creditcard_center.withdraw()  86             elif int(user_choice) == 3:  87                 print("轉帳".center(50, "-"))  88  creditcard_center.transfer()  89             elif int(user_choice) == 4:  90                 print("還款".center(50, "-"))  91  creditcard_center.repay()  92             elif int(user_choice) == 5:  93                 print("流水記錄".center(50, "-"))  94  creditcard_center.credit_check(credit_card)  95             elif int(user_choice) == 6:  96                 print("申請信用卡".center(50, "0"))  97                 creditcard_center.apply_creditcard(limit=15000, locked="true")  98             elif int(user_choice) == 7:  99                 print("返回".center(50, "-")) 100                 break
101         else: 102             print("無效的字符") 103 
104 
105 # 後臺管理
106 def option_backadmin(user): 107     while True: 108         print('後臺管理'.center(50, '-')) 109         option_list = ["添加帳戶", "鎖定帳戶", "解鎖帳戶", "凍結信用卡","解凍信用卡", "返回"] 110         count = 0 111         for option in option_list: 112             count += 1
113             print(str(count) + '.' + option) 114         user_choice = input('>>>:') 115         if user_choice.isdecimal(): 116             if int(user_choice) == 1: 117                 print("添加帳戶".center(50, "-")) 118  admin_center.add_user() 119             elif int(user_choice) == 2: 120                 print("鎖定帳戶".center(50, "-")) 121  admin_center.lock_user() 122             elif int(user_choice) == 3: 123                 print("解鎖帳戶".center(50, "-")) 124  admin_center.unlock_user() 125             elif int(user_choice) == 4: 126                 print("凍結信用卡".center(50, "-")) 127  admin_center.lock_creditcard() 128             elif int(user_choice) == 5: 129                 print("解凍信用卡".center(50, "-")) 130  admin_center.unlock_creditcard() 131             elif int(user_choice) == 6: 132                 print("返回".center(50, "-")) 133                 break
134         else: 135             print("無效的字符") 136 
137 
138 # 認證模塊
139 while True: 140     print("歡迎進入信用卡網購程序".center(50, "-")) 141     option_list = ["購物中心", "信用卡中心", "後臺管理", "退出"] 142     count = 0 143     for option in option_list: 144         count += 1
145         print(str(count) + '.' + option) 146     user_choice = input(">>>:") 147     if user_choice.isdecimal(): 148         if int(user_choice) == 1: 149  option_shopping(authenticate.user_auth()) 150         elif int(user_choice) == 2: 151  option_creditcard(authenticate.creditcard_auth()) 152         elif int(user_choice) == 3: 153  option_backadmin(authenticate.admin_auth()) 154         elif int(user_choice) == 4: 155             print("再見!") 156             break
157     else: 158         print("無效的字符")
main

5 database目錄中文件json

1 { }
user
1 # 默認爲空
shopping_record
1 # 默認爲空
shopping_cart
1 IPhone 8800
2 Mac-Pro 12388
3 IPad 4999
4 Mouse 181
5 Bike 800
6 keyboard 199
7 Dell-Screen 5999
8 Nike-Watch 999
production_list
1 # 默認爲空
creditcard_record
1 { }
creditcard_info

6 log目錄文件api

1 # 默認爲空
user_flowlog

7 我的理解數據結構

  編程序,要多動手,纔會有更多的收穫。光靠看去思考,轉瞬就忘,不會有長久的記憶,更談不上有深入的理解。app

  本身寫的或者抄寫的代碼,也要常常回頭看看,增強本身的理解。ide

  函數之間,要有兩個空行。

  換行適用「\」符號,可是若是是括號內換行,則可不使用。

  使用條件語句時,若有必要,if於對應的else要成對出現。

  要深入理解python語言的思想精髓,打好本身的基礎。

  複雜的程序要有模塊化的思惟,任何程序要肯定數據結構(是列表,仍是字典),其次是要實現的方法(動做),最後是業務邏輯。

8 思路來源

  http://www.cnblogs.com/lianzhilei/p/5786223.html

  https://www.cnblogs.com/Mr-hu/articles/7423088.html

  https://www.jianshu.com/p/734931a76bc1

  https://www.cnblogs.com/garrett0220/articles/6861418.html

相關文章
相關標籤/搜索