1. 程式人生 > >ATM和購物商城-錯題集

ATM和購物商城-錯題集

clas 余額 遍歷 roc color pgm 打印 交易 帳戶

1、獲取當前月份前一個月月份

import datetime
aaa = ((datetime.datetime.now() + datetime.timedelta(days = -30))).strftime("%Y%m")
print(aaa)

2、遍歷目錄

os.walk(dir_name)

def go_though():
    ‘‘‘
    遍歷指定目錄
    ‘‘‘
    db_path = db_handler.db_handler(settings.DATABASE)
    # 獲取路徑,目錄,文件名稱
    for root, dirs, files in
os.walk(db_path): print("root:%s, dirs:%s files:%s" % (root,dirs,files)) for f in files: # 判斷是否存在.json結尾的文件 if os.path.splitext(f)[1] == ".json": # 獲取賬戶ID account_id = os.path.splitext(f)[0] # 帳戶id # account_file = "%s/%s.json" % (db_path, account_id)
# account_data = auth.check_account(account_id) # 獲取用戶信息 account_data = auth.ck_acc_data(account_id) # 判斷用戶權限是否為管理員 if account_data: status = account_data[status] # print(status) print
("Account bill:".center(50, "-")) # 除了管理員,普通帳戶都應該出帳單,即使帳戶禁用 if status != 8: # print("status != 8 ",account_id) auth.display_account_info(account_data) get_user_bill(account_id) # 獲取帳單 print("End".center(50, "-")) return True 3、用戶登錄次數驗證 def acc_login(user_data,log_obj): ‘‘‘ 判斷用戶登錄錯誤次數,超過3次記錄日誌和打印屏幕輸出,使用字典方式支持多用戶互相切換錯誤記錄 :param user_data: :param log_obj: access_logger :return: auth = account_data ‘‘‘ account_login_dic = {} retry_count = 0 exit_count = 4 while user_data[is_authorized] is False and retry_count < exit_count: account = input(\033[32;1m請輸入賬戶ID:\033[0m.strip()) password = input(\033[32;1m請輸入密碼:\033[0m.strip()) # 判斷用戶正確性,用戶正確則初始化用戶數據狀態 auth = acc_auth(account,password) if auth: user_data[is_authorized] = True user_data[account_id] = account return auth else: #先檢測 dic 裏面是否有相同名稱 的key,沒有就增加,有就取value if account not in account_login_dic: # 如果賬戶不存在於字典 count = 0 count += 1 account_login_dic.update({account:count}) # 初始化新用戶到字典 else: count = account_login_dic[account] # 初始化 計數 count += 1 # 到此處錯誤已經產生,錯誤次數+1 account_login_dic.update({account:count}) # 將用戶對應錯誤次數更新到字典 # print("old",account_login_dic) for i in account_login_dic.values(): # 判斷字典中用戶名對應的 錯誤次數 retry_count = i # print(retry_count) if retry_count == 3: # 判斷用戶是否產生3次錯誤,3次錯誤 記錄日誌 並且 退出當前程序 curr_account = list(account_login_dic.keys())[list(account_login_dic.values()).index(retry_count)] # print(curr_account) # 記錄用戶錯誤行為日誌 log_obj.error(" [%s] have try too many attempts,System exit!" % (curr_account)) exit() 4、初始化用戶數據到字典,再將字典寫入數據文件 curr_day = datetime.datetime.now().strftime("%Y-%m-%d") # 當前日期 yesterday = datetime.datetime.now() + datetime.timedelta(days=-1) # 昨天日期 after_3_years_day = yesterday.replace(year=(int(yesterday.strftime("%Y")) + 3)) # 三年後的昨天(過期時間) expire_day = after_3_years_day.strftime(%Y-%m-%d) # 過期日期 pay_day = 22 # 還款日 account_data = { enroll_date: curr_day, password: password, id: account, credit: 15000, status: 0, balance: 0.0, expire_date: expire_day, pay_day: pay_day } # 存儲新用戶數據 accounts.dump_account(account_data) 5、空格分隔數據 # 格式化輸出結果,a,b間隔20個空格,以‘:‘ 分隔,b變色 print("{:<20}:\033[32;1m{:<20}\033[0m".format(a,b)) 6、密碼加密 def get_md5(password): ‘‘‘ 用戶密碼加密 :param password: :return: ‘‘‘ # 獲取 md5 md5 = hashlib.md5() md5.update(password) return md5.hexdigest() 7、日誌記錄函數 def logger(log_type): ‘‘‘ 日誌輸出和記錄 :param log_type: :return: ‘‘‘ logger = logging.getLogger(log_type) logger.setLevel(settings.LOG_LEVEL) # 屏幕輸出 screen output show ch = logging.StreamHandler() ch.setLevel(settings.LOG_LEVEL) # 屏幕 輸出 info # 日誌文件輸出 logs file output log_file = "%s/logs/%s" % (settings.BASE_DIR,settings.LOG_TYPES[log_type]) # print(log_file) fh = logging.FileHandler(log_file) fh.setLevel(settings.LOG_LEVEL) # 日誌記錄 info #日誌輸出格式 formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s,datefmt=%Y-%m-%d %H:%M:%S) ch.setFormatter(formatter) fh.setFormatter(formatter) #屏幕輸出和日誌輸出加入到logger logger.addHandler(ch) logger.addHandler(fh) #返回輸出 return logger 8、根據傳入類型函數進行操作函數 類型為在配置中定義值 TRANSACTION_TYPE = { repay: {action: plus, interest: 0}, # 還款 receive: {action: plus, interest: 0}, # 接收 withdraw: {action: minus, interest: 0.05}, # 提款 transfer: {action: minus, interest: 0.05}, # 轉出 pay: {action: minus, interest: 0}, # 支付 save: {action: plus, interest: 0}, # 存錢 } def make_transaction(log_obj,account_data,trans_type,amount,**others): ‘‘‘ 用戶金額操作改動數據後存儲日誌,改動後返回用戶數據 :param log_obj: :param account_data: :param trans_type: :param amount: :param others: :return:account_data ‘‘‘ # 金額轉換浮點類型 amount = float(amount) # 判斷 交易類型 if trans_type in settings.TRANSACTION_TYPE: # 交易類型存在 interest = amount * settings.TRANSACTION_TYPE[trans_type][interest] # 定義利息 old_balance = account_data[balance] # 初始化 交易前的值 # 根據交易類型,對金額進行加減操作,並減除帶有利息的操作 if settings.TRANSACTION_TYPE[trans_type][action] == plus: new_balance = old_balance + amount + interest account_data[balance] = new_balance accounts.dump_account(account_data) elif settings.TRANSACTION_TYPE[trans_type][action] == minus: new_balance = old_balance - amount - interest if new_balance < 0: print("\033[32;1m 您的信用額度為:[%s],您的額度不支持本次操作[-%s],您當前的余額為:[%s]\033[0m" %(account_data[credit],(amount +interest),old_balance)) return False account_data[balance] = new_balance accounts.dump_account(account_data) # log_obj = transaction_logger = logger.logger(‘transaction‘) # 將操作記錄到日誌文件 log_obj.info("accounts:%s action:%s amount:%s interest:%s " %(account_data[id],trans_type,amount,interest)) return account_data else: print("您的選項有誤或不存在:%s"%(trans_type)) 9、接口調用流程 調用方: 以充值為例: atm_api = os.path.dirname(BASE_DIR) + "/Atm/api/pay_api.py" # 定義 接口文件和金額 comm = "python " + atm_api + " " + charge # 創建 調用進程,執行指定的comm pgm = subprocess.Popen(comm,shell=True) # 接口文件交互 pgm.communicate() if pgm.returncode == 0: print("\033[31;1m付款成功\033[0m") # 充值成功後,更新用戶余額 acc_data[balance] += float(charge) # 將用戶余額存入賬戶 accounts.dumpAccount(acc_data) print("您的余額為:%s"%acc_data[balance]) else: print("充值失敗!") 被調用方 入口 pay_api.py # 取金額參數 amount = sys.argv[1] # 執行接口程序調用,定義退出 rlt = main.payApi(amount) if rlt: exit(0) else: exit(1) def payApi(amount): ‘‘‘ 交易接口,提供給其他消費方式調用 :param amount: :return: ‘‘‘ amount = int(amount) acc_data = get_user_data() # print("\033[42;1m payApi \033[0m",acc_data) # 根據獲取到的用戶id 獲取用戶數據 account_data = accounts.load_balance(acc_data[account_id]) # 判斷交易金額 是否大於,交易大於0 則進行交易操作 if amount > 0: new_balance = transaction.make_transaction(transaction_logger,account_data,pay,amount) if new_balance: return True else: print("你的輸入 [%s] 有誤,請輸入數字金額"% amount) return None

ATM和購物商城-錯題集