日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python atm作业详解_python day4 作业 ATM

發布時間:2024/9/15 python 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python atm作业详解_python day4 作业 ATM 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

作業需求

指定最大透支額度

可取款

定期還款(每月指定日期還款,如15號)

可存款

定期出賬單

支持多用戶登陸,用戶間轉帳

支持多用戶

管理員可添加賬戶、指定用戶額度、凍結用戶等

目錄結構如下:

ATM2/

├── bin

│?? ├── admin_user.py? ##管理員進入界面

│?? ├── atm_user.py? # 普通用戶進入界面

│?? └── __init__.py

├── conf

│?? ├── __init__.py

│?? ├── __pycache__

│?? │?? ├── __init__.cpython-36.pyc

│?? │?? └── settings.cpython-36.pyc

│?? └── settings.py? # 主配置文件 (首先看這個)

├── core

│?? ├── accounts.py? ?# 用戶數據json 文件

│?? ├── auth.py? ? ? ? ?# 用戶認證

│?? ├── bill_date.py? ? # 時間格式

│?? ├── db_handler.py? # 數據庫

│?? ├── __init__.py

│?? ├── logger.py? ? ?#log 文件

│?? ├── main.py? ? ?# 主函數

│?? ├── __pycache__

│?? │?? ├── accounts.cpython-36.pyc

│?? │?? ├── auth.cpython-36.pyc

│?? │?? ├── bill_date.cpython-36.pyc

│?? │?? ├── db_handler.cpython-36.pyc

│?? │?? ├── __init__.cpython-36.pyc

│?? │?? ├── logger.cpython-36.pyc

│?? │?? ├── main.cpython-36.pyc

│?? │?? └── transaction.cpython-36.pyc

│?? └── transaction.py

├── db

│?? ├── accounts

│?? │?? ├── admin.json

│?? │?? ├── liang2.json

│?? │?? └── liang.json

│?? └── __init__.py

├── __init__.py

└── log

├── access.log

├── accounts

├── __init__.py

└── transactions.log

說下心得哈。首先我。我也是第一次寫這種代碼 最開始的時候一個文件相互調來調去的確實繁瑣,

后面看ygqygq2?老哥寫的,豁然開朗。第一步就是看代碼。先把代碼一行行去讀起來。因為我也沒

學多久。久久看了兩天才把老哥的代碼看懂。實在沒辦法。 還有就是看代碼的順序。第一看的是配置

文件,后面你文件頭里面的import 是那個文件,這樣以此類推的看下去。

我的代碼還是有點問題,沒有老哥的代碼寫的完美。那么上代碼把

settings.py

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

importsys,os,logging

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

sys.path.append(BASE_DIR)

BILL_DAY=25DATABASE={'engine':'file_storage','name':'accounts','path':'%s/db' %BASE_DIR

}

LOG_LEVEL=logging.INFO

LOG_TYPES={'transaction':'transactions.log','access':'access.log',

}

LOG_DATABASE={'engine': 'file_storage','name': 'accounts','path': '%s/log' %BASE_DIR

}

TRANSACTION_TYPE={'repay':{'action':'plus','interest':0}, #還款

'receive':{'action':'plus','interest':0}, #接受

'withdraw':{'action':'munus','interest':0.05}, #提款

'transfer':{'action':'minus','interest':0.05}, #轉出

'pay':{'action':'minus','interest':0}, #支付

'sava':{'action':'plus','interest':0}, #存錢

}

ACCOUNT_FORMAT={'''用戶數據格式

{"enroll_date": "2016-01-02", "password": "abc", "id": 1000, "credit": 15000,

"status": 0, "balance": 1000.0, "expire_date": "2021-01-01", "pay_day": 22}'''}

View Code

db_handler.py

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

deffile_db_handle(conn_params):'''存放數據的文件路徑

:param conn_params:

:return:'''db_path='%s/%s' %(conn_params['path'],conn_params['name'])returndb_pathdefdb_handler(conn_parms):'''數據庫類型

:param conn_parms:

:return:'''

if conn_parms['engine']=='file_storage':returnfile_db_handle(conn_parms)elif conn_parms['engine']=='mysql':pass

View Code

auth.py

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

importos,sys

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

sys.path.append(BASE_DIR)importosfrom core importdb_handlerfrom core importaccountsfrom conf importsettingsimportjsonimportdatetimedefacc_auth(account,password):'''用戶驗證函數

:param account:

:param password:

:return:'''db_path=db_handler.db_handler(settings.DATABASE)

account_file="%s/%s.json" %(db_path,account)ifos.path.isfile(account_file):

with open(account_file) as f:

account_data=json.load(f)if account_data["password"] ==password:

exp_time_stamp=datetime.datetime.strptime(account_data['expire_date'], "%Y-%m-%d")

status=account_data['status']if datetime.datetime.now() >exp_time_stamp:print("%s賬戶已近過期了.請聯系管理員"%account)elif status == 0 or status == 8:returnaccount_dataelse:print("賬戶已經過期了。或者不是管理員!!")else:print("密碼錯誤")else:print("文件不存在")defacc_login(user_data,log_obj):'''用戶登錄 的函數

:param user_data:

:param log_obj:

:return:'''exit_count=3 #登錄次數

retry_connt=0 #初始化重試數據

same_account=0 #輸入時。相同數據計數

last_account="" #初始化上一次輸入的用戶

while user_data['is_authenticated'] is not True and retry_connt

account=input("請輸入用戶名:").strip()

password=input("請輸入密碼").strip()if account==last_account:

same_account+=1auth=acc_auth(account,password)

last_account=accountifauth:

user_data['is_authenticated']=True

user_data['account_id']=accountreturnauth

retry_connt+=1

else:if same_account==exit_count -1:

log_obj.error("account [%s] too many login attempts" %account)

exit()defacc_check(account):'''查詢賬戶是否存在

:param account:

:return:'''db_path=db_handler.db_handler(settings.DATABASE)

account_file="%s/%s.json" %(db_path,account)ifos.path.isfile(account_file):

with open(account_file,'r') as f:

account_data=json.load(f)

status=account_data["status"]

exp_time_stamp=datetime.datetime.strptime(account_data['expire_date'],"%Y-%m-%d")if datetime.datetime.now()>exp_time_stamp:print("此%s賬戶已經過期。請聯系管理員"%account)else:returnaccount_dataelse:returnFalsedefsign_up():'''用戶注冊和admin 管理員用戶

:return:'''pay_dat=22exit_flag=Truewhile exit_flag isTrue:

account=input("請輸入你的用戶名:").strip()

password=input("請輸入你的密碼:").strip()

exit_flag=acc_check(account)ifexit_flag:print("次用戶已經存在。請選擇其他用戶名")else:#現在的時間格式

today=datetime.datetime.now().strftime("%Y-%m-%d")#默認五年后過期

after_5_years=int(datetime.datetime.now().strftime('%Y')) +5

#五年后的今天

after_5_years_today=datetime.datetime.now().replace(year=after_5_years)#五年后的昨天

expire_day=(after_5_years_today + datetime.timedelta(-1)).strftime('%Y-%m-%d')"""用戶數據庫格式

{"enroll_date": "2016-01-02", "password": "abc", "id": 1000, "credit": 15000,"balance":0,

"status": 0, "balance": 1000.0, "expire_date": "2021-01-01", "pay_day": 22}"""account_data={"enroll_date":today,"password":password,"id":account,"credit":15000,"balance":0,"status":0,"expire_date":expire_day,"pay_day":pay_dat}print(account_data)

accounts.dump_account(account_data)print("添加成功 用戶ID:[%s]!!!" %account)returnTruedefmodify():'''修改用戶信息

:return:'''items=["password","credit","status","expire_day","pay_day"]

acc_data=False

contine_flag=Falsewhile acc_data isFalse:

account=input("請輸入你要修改的用戶名:").strip()#丟到驗證函數中

account_data=acc_check(account)if account_data isFalse:print("你輸入的用戶不存在")else:while contine_flag is notTrue:#判斷輸入json 格式

print('''請你輸入json 格式

{

"password": "abc",

"credit": 15000,

"status": 0,

"expire_date": "2021-01-01",

"pay_day": 22

}''')

modify_items=input("請你輸入json格式").strip()try:

modify_items=json.loads(modify_items)exceptException as e:print("輸入錯誤!!!")continueerror_flag=False #初始化錯誤標記

for index inmodify_items:if index initems:#修改用戶數據 就是字典修改方式

account_data[index]=modify_items[index]else:print("輸入有錯誤!!!")continue

iferror_flag:continue

#再寫到文件中

accounts.dump_account(account_data)print("修改成功!!!")

contine_flag=True

acc_data=Truereturn True

View Code

accounts.py

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

importjsonimporttimefrom core importdb_handlerfrom conf importsettingsdefload_current_balance(account_id):'''json load 用戶文件

:param account_id:

:return:'''db_path=db_handler.db_handler(settings.DATABASE)#db_path 調用的是配置文件的DATABASE路徑

#db_path 完整的路徑是 ATM\db\accounts

account_file="%s/%s.json" %(db_path,account_id)

with open(account_file,'r') as f:

acc_data=json.load(f)returnacc_datadefdump_account(account_data):'''寫到文件當中

:param account_data:

:return:'''db_path=db_handler.db_handler(settings.DATABASE)#這個數據的目錄 ATM\db\accounts

account_file="%s/%s.json" %(db_path,account_data['id'])

with open(account_file,'w') as f:

acc_data=json.dump(account_data,f)return True

View Code

bill_date.py

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

from conf importsettingsimportdatetimedefget_bill_time(year_month):'''獲取給出的年-月的信用卡賬單 月份起止時間

:param year_month: 年-月

:return: 返回時間'''the_bill_day="%s-%s" %(year_month,settings.BILL_DAY)

bill_begin_time=datetime.datetime.strptime(the_bill_day,"%Y-%m-%d")

year=bill_begin_time.year

month=bill_begin_time.monthif month ==12:

month=1year+=1

else:

month+=1bill_end_time=datetime.datetime(year,month,settings.BILL_DAY)return bill_begin_time,bill_end_time

View Code

transaction.py

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

from conf importsettingsfrom core importaccountsfrom core importlogger#transaction logger

def make_transaction(log_obj, account_data, tran_type, amount, **others):'''deal all the user transactions

:param account_data: user account data

:param tran_type: transaction type

:param amount: transaction amount

:param others: mainly for logging usage

:return:'''

#交易金額 為浮點型

amount =float(amount)#判斷交易類型是否在存在里面

if tran_type insettings.TRANSACTION_TYPE:#利息的計算

interest = amount * settings.TRANSACTION_TYPE[tran_type]['interest']#我現有的金額

old_balance = account_data['balance']#判斷是否是加金額

if settings.TRANSACTION_TYPE[tran_type]['action'] == 'plus':#金額的加 是 本金+交易金額+ 利息

new_balance = old_balance + amount +interest#如果為減

elif settings.TRANSACTION_TYPE[tran_type]['action'] == 'minus':#那就是 本金 減 交易金額 減 利息

new_balance = old_balance - amount -interest#check credit

#減去了 所有的 如果大于0

if new_balance <0:#輸出用戶的額度 、 減少了多少金額 、剩下了多少額度

print('''Your credit [\033[31;1m%s\033[0m] is not enough for this transaction [-%s],

your current balance is [\033[32;1m%s\033[0m]'''

% (account_data['credit'], (amount +interest), old_balance))return

#把用戶剩余的額度 寫入到文件中

account_data['balance'] =new_balance#json 序列化到文件中

accounts.dump_account(account_data) #save the new balance back to file

#輸出用戶的用戶名、交易類型、交易金額、利息

log_obj.info("account:%s action:%s amount:%s interest:%s" %(account_data['id'], tran_type, amount, interest))#返回最新的用戶數據

returnaccount_data#不存在的交易類型

else:print("\033[31;1mTransaction type [%s] is not exist!\033[0m" %tran_type)#from conf import settings#from core import accounts#from core import logger#

#

#

#

#

#def make_transaction(log_obj,account_data,tran_type,amount,**kwargs):#'''#交易函數#:param log_obj: log#:param account_data: 用戶數據#:param tran_type: 交易類型#:param amount: 金額action#:param kwargs: 主要用于日志#:return:#'''##交易金額 為浮點型#amount=float(amount)#

#if tran_type in settings.TRANSACTION_TYPE:#

##利息的計算#interest=amount *settings.TRANSACTION_TYPE[tran_type]['interest']#print(interest)## 現有的余額#old_balance= account_data['balance']#

##判斷是否加金額#if settings.TRANSACTION_TYPE[tran_type]['action'] == 'plus':## 金額 就是本金+交易金額+利息#new_balance=old_balance+amount+interest#print(new_balance)##如果是減去#elif settings.TRANSACTION_TYPE[tran_type]['action']=='minus':#new_balance=old_balance-amount-interest#if new_balance<0:#print("你的額度為%s .你本次交易的金額(+利息的)%s 你的余額為%s"%(account_data['credit'],(amount+interest),account_data['old_balance']))#return None##把用戶更新的額度寫入到文件中#account_data['balance']= new_balance#

## json 序列化到文件中#xx=accounts.dump_account(account_data)## 輸出用戶的用戶名、交易類型、交易金額、利息#log_obj.info("account:%s action:%s amount:%s interest:%s" %#(account_data["id"],tran_type,amount,interest))#

#return xx#

#else:#print("錯誤類型")## money=input("輸入需要存款的數量:>>>")## account_data={'enroll_date': '2018-01-31', 'password': '123456', 'id': 'liang', 'credit': 15000, 'balance': 0, 'status': 0, 'expire_date': '2023-01-30', 'pay_day': 22}#### x=make_transaction(trans_logger,account_data,'sava',money)## print(x)

View Code

logger.py

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

importloggingimportdatetimefrom conf importsettingsfrom core importbill_datedeflogger(log_type):#創建loggin

logger =logging.getLogger(log_type)

logger.setLevel(settings.LOG_LEVEL)#create console handler and set level to debug

ch =logging.StreamHandler()

ch.setLevel(settings.LOG_LEVEL)#create file handler and set level to warning

#創建 log 文件的一個級別

log_file = "%s/log/%s" %(settings.BASE_DIR, settings.LOG_TYPES[log_type])

fh=logging.FileHandler(log_file)

fh.setLevel(settings.LOG_LEVEL)#create formatter

#log的輸入格式

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')#add formatter to ch and fh

ch.setFormatter(formatter)

fh.setFormatter(formatter)#add ch and fh to logger

logger.addHandler(ch)

logger.addHandler(fh)returnlogger#'application' code

'''logger.debug('debug message')

logger.info('info message')

logger.warn('warn message')

logger.error('error message')

logger.critical('critical message')'''

defshow_log(account, log_type, year_month):"""顯示日志內容

:param user_name: 用戶名

:param log_type: 日志類型

:return:"""

#給出的賬單時間 結束的賬單時間

begin_time, end_time =bill_date.get_bill_time(year_month)#log文件的所在路徑

log_file = "%s/log/%s" %(settings.BASE_DIR, settings.LOG_TYPES[log_type])#打開log文件

file =open(log_file)print("-".center(50, "-"))for line infile:#log 時間

log_time = datetime.datetime.strptime(line.split(",")[0], "%Y-%m-%d %H:%M:%S")#記錄的用戶

user_name = line.split()[7].split(":")[1]#帳單生成日是25號,則每月帳單是從上月25日到本月24日之間

if account == user_name and begin_time <= log_time

file.close()#import os,sys#BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#sys.path.append(BASE_DIR)#import logging#import datetime#from conf import settings#from core import bill_date#

#

#def logger(log_type):#

##創建loggin#logger=logging.getLogger(log_type)#logger.setLevel(settings.LOG_LEVEL)#

#ch=logging.StreamHandler()#ch.setLevel(settings.LOG_LEVEL)#

## 創建log 文件 級別#log_file="%s/log/%s" %(settings.BASE_DIR,settings.LOG_TYPES[log_type])#fh =logging.StreamHandler(log_file)#fh.setLevel(settings.LOG_LEVEL)#

##log 的輸入格式#formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')#

#ch.setFormatter(formatter)#fh.setFormatter(formatter)#

#return logger#

#def show_log(account,log_type,year_month):#'''#顯示 日志內容#:param account: 用戶 名#:param log_type: 日志類型#:param year_month:#:return:#'''## 給出賬單 時間 結束時間#begin_time,end_time=bill_date.get_bill_time(year_month)## log 文件路徑#log_file="%s/log/%s" %(settings.BASE_DIR,settings.LOG_TYPES[log_type])#

## 打開log文件#file=open(log_file,'r')#print("-".center(50,"-"))#for line in file:## log 時間#log_time=datetime.datetime.strptime(line.split(",")[0],"%Y-%m-%d %H:%M:%S")## 記錄用戶#user_name=line.split()[7].split(":")[1]##賬單生成日是25 號 則每月賬單是從上月25到本月24之間#if account==user_name and begin_time<=log_time

#

#

#

#x=logger('transaction')#x.info("account:%s action:%s amount:%s interest:%s" %('liang','tran_type','amount','interest'))

View Code

main.py

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

importos,sys

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

sys.path.append(BASE_DIR)from core importauthfrom core importloggerfrom core importaccountsfrom core importtransactionfrom core importdb_handlerfrom conf importsettingsimportdatetimeimporttimeimportos#建立transaction.log 文件

trans_logger=logger.logger('transaction')#建立 access.log 文件

access_logger=logger.logger('access')#臨時賬戶數據、僅保存在內存中

user_data={'account_id':None,'is_authenticated':False,'account_data':None

}defdisp_account_info(account_data):'''格式化輸出賬戶信息(管理員可直接使用)

#去除 password 字段顯示

:param account_data: 賬戶信息

:return:'''ignore_display=["password"]for k inaccount_data:if k inignore_display:continue

else:print("{:<20}:\033[32;1m{:<20}\033[0m".format(k, account_data[k]))defadmin_account_info(acc_data):'''管理員查看其它用戶

:param acc_data:

:return:'''user_id=acc_data["account_id"]

account_data=acc_data["account_data"]

status=account_data["status"]if status ==8:

admin_input_id=input("請輸入你需要查詢的ID").strip()

new_user_info=auth.acc_check(admin_input_id)

new_user_status=new_user_info["status"]if new_user_status ==8:if user_id==admin_input_id:

disp_account_info(new_user_info)returnTrueelse:print("你能查詢其它管理員【%s】的信息"%(admin_input_id))elif new_user_info !=8:

disp_account_info(new_user_info)else:

exit("非法操作")defaccount_info(acc_data):'''普通用戶打印登錄用戶信息

:param acc_data: 登錄信息

:return:'''

#用戶ID

account_id=acc_data["account_id"]# account_data=acc_data["account_data"]# status=account_data["status"]# if status !=8:

disp_account_info(account_data)returnTrueelse:

exit("謝謝!!!!!")defget_user_data():'''登錄并獲取新的user-data

:return:'''account_data=auth.acc_login(user_data,access_logger)if user_data["is_authenticated"]:#此刻就是有數據了

user_data["account_data"]=account_data#返回最新用戶數據

returnuser_dataelse:returnNonedefpay(amount):'''消費付款

:param amount: 付款金額

:return:'''

#用戶數據

acc_data=get_user_data()

account_data=accounts.load_current_balance(acc_data['account_id'])if amount>0:#new_balance 是用戶的最新數據。有兩個結果 。一個是None 一個是用戶數據

new_balance=transaction.make_transaction(trans_logger,account_data,'pay',amount)ifnew_balance:returnTrue#小于0

else:print("你輸入的金額需要大于0%s"%amount)returnNonedefrepay(acc_data):'''還款

:param acc_data:

:return:'''

print(acc_data)

account_data= accounts.load_current_balance(acc_data['account_id'])

current_blance='''-------- balance info ---------

Credit : %s

Balance: %s'''%(account_data['credit'],account_data['balance'])print(current_blance)

back_flag=Falsewhile notback_flag:print("按b退出")#還款金額

reap_amount=input("請輸入你還款的金額:>>").strip()if len(reap_amount) >0 andreap_amount.isdigit():#new_balance = 用戶最新數據

new_balance=transaction.make_transaction(trans_logger,account_data,'repay',reap_amount)

time.sleep(0.1)ifnew_balance:print("你的余額為%s"%(new_balance['balance']))elif reap_amount =='b':

back_flag=Trueelse:print("輸入錯誤。請從新輸入!!!!%s"%(reap_amount))defwithdraw2(acc_data):'''提款

:param acc_data:

:return:'''

#用戶最新數據

account_data=accounts.load_current_balance(acc_data['account_id'])

current_blance='''-------- balance info ---------

Credit : %s

Balance: %s'''%(account_data['credit'],account_data['balance'])print(current_blance)

back_flag=Falsewhile notback_flag:print("輸入b 跳出")

withdrwa_amount=input("請輸入提款金額:>>>").strip()if len(withdrwa_amount)>0 andwithdrwa_amount.isdigit():

new_balance2=transaction.make_transaction(transaction,account_data,'withdraw',withdrwa_amount)

time.sleep(0.1)ifnew_balance2:print("你剩余的余額%s" %new_balance2['balance'])elif withdrwa_amount=='b':

back_flag=Trueelse:print("你輸入錯誤!!!%s"%withdrwa_amount)defwithdraw(acc_data):'''提款

print current balance and let user do the withdraw action

:param acc_data:

:return:'''

#用戶最新數據

account_data = accounts.load_current_balance(acc_data['account_id'])#格式化輸出用戶的 額度+ 用戶的賬目

current_balance = '''--------- BALANCE INFO --------

Credit : %s

Balance: %s''' % (account_data['credit'], account_data['balance'])print(current_balance)

back_flag=Falsewhile notback_flag:print("Tip: [b] to back")#輸入還款金額

withdraw_amount = input("\033[33;1mInput withdraw amount:\033[0m").strip()#長度大于0 并且是數字

if len(withdraw_amount) > 0 andwithdraw_amount.isdigit():#返回用戶最新的數據

new_balance = transaction.make_transaction(trans_logger, account_data, 'withdraw', withdraw_amount)

time.sleep(0.1) #處理顯示問題

#如果有數據, 就顯示現有的賬目

ifnew_balance:print('''\033[42;1mNew Balance:%s\033[0m''' % (new_balance['balance']))elif withdraw_amount == 'b':

back_flag=Trueelif withdraw_amount == 'q' and withdraw_amount == 'exit':

exit("謝謝下次再來")break

else:print('[\033[31;1m%s\033[0m] is not a valid amount, only accept integer!' %withdraw_amount)deftransfer(acc_data):'''打印出當前余額 并轉錢

:param acc_data:

:return:'''

#用戶最近數據

account_data=accounts.load_current_balance(acc_data['account_id'])#顯示用戶的額度

current_blance='''-------- balance info ---------

Credit : %s

Balance: %s'''%(account_data['credit'],account_data['balance'])print(current_blance)

back_flag=Falsewhile notback_flag:#輸入轉給誰 .不能轉給自己

recevier=input("輸入你需要轉錢的用戶:>>>>").strip()if str(recevier)==str(account_data["id"]):print("不能轉給自己")continue

elif recevier=='b':

back_flag=Trueelse:#檢查是否有這個ID

receiver_account_data=auth.acc_check(recevier)#判斷這個Id 是否過期和是不是普通用戶

status=receiver_account_data["status"]print(status)if status ==0:#如果等于0就讓他輸入金額

transfer_amount=input("輸入你需要轉的金額:>>")if len(transfer_amount) >0 andtransfer_amount.isdigit():

new_blance=transaction.make_transaction(trans_logger,account_data,'transfer',transfer_amount)

transaction.make_transaction(trans_logger,receiver_account_data,'receive',transfer_amount)ifnew_blance:

time.sleep(0.2)print("轉錢成功!!!")else:print("請輸入大于0的金額!!!!")if transfer_amount=='b':

back_flag=Trueelse:print("不能轉為其他人")defpay_check(acc_data):'''查詢賬單詳情

:param acc_data:

:return:'''bill_data=input("請輸入你需要查詢的年月份 例如[2018-01]:>>>>").strip()

log_path=db_handler.db_handler(settings.DATABASE)

bill_log="%s/%s.bills" %(log_path,acc_data["account_id"])if notos.path.exists(bill_log):print("沒有記錄用戶[%s]"%acc_data["account_id"])return

print("請輸入你需要查詢的ID %s"%acc_data["account_id"])print("-".center(50,'#'))

with open(bill_data,'r') as f:for bill inf:print(bill)

b_data=bill.split(" ")[0]if bill_data==b_data:print("%s"%bill.strip())

log_type="transactions"

print("%s" %acc_data["account_id"])

logger.show_log(acc_data["account_id"],log_type,bill_data)defsave(acc_data):'''存錢

:param acc_data:

:return:'''account_data=accounts.load_current_balance(acc_data["account_id"])print(account_data)

current_balance= '''--------- BALANCE INFO --------

Credit : %s

Balance: %s

(Tip: input [b] to back)''' % (account_data['credit'], account_data['balance'])print(current_balance)

back_flag=Falsewhile notback_flag:#輸入存款金額

save_amount=input("輸入你需要存款的金額:>>>").strip()if save_amount == 'b':

back_flag=Trueelif len(save_amount) > 0 andsave_amount.isdigit():

new_balance= transaction.make_transaction(trans_logger, account_data, 'save', save_amount)

time.sleep(0.1) #解決日志顯示問題

ifnew_balance:print('''\033[42;1mNew Balance:%s\033[0m''' % (new_balance['balance']))

back_flag=Trueelse:print('[\033[31;1m%s\033[0m] is not a valid amount, only accept integer!' %save_amount)deflogout(acc_data):'''清除認證信息、退出

:param acc_data:

:return:'''exit("謝謝!!!!".center(50,'#'))definteractive(acc_data):'''普通用戶界面

:param acc_data:

:return:'''status=acc_data["account_data"]["status"]if status==8:print("管理員不能查看!!%s"%acc_data["account_id"])

menu=u'''----------- user bank ------------

1. 賬戶信息

2. 還款

3. 取款

4. 轉賬

5. 存款

6. 賬單

7. 退出'''menu_dic={'1':account_info,'2':repay,'3':withdraw,'4':transfer,'5':save,'6':pay_check,'7':logout,

}

exit_flag=Falsewhile notexit_flag:print(menu)

user_option=input(":>>>").strip()if user_option inmenu_dic:#print(acc_data)

menu_dic[user_option](acc_data)else:print("輸入錯誤!!!")defget_bill(account_id):'''生成賬單 、定義每月25 日

:param account_id:

:return:'''

#當前時間

i =datetime.datetime.now()

year_month="%s-%s" %(i.year,i.month)

account_data=accounts.load_current_balance(account_id)

balance=account_data["balance"]#可用額度

credit=account_data["credit"]if i.day !=settings.BILL_DAY:print("\033[31;1mToday is not the bill generation day!\033[0m")if balance>=credit:

repay_amount=0

bill_info="Account [\033[32;1m%s\033[0m] needn't to repay." %account_idelse:

repay_amount=credit-balance

bill_info="Account [\033[32;1m%s\033[0m] need to repay [\033[33;1m%s\033[0m]"\%(account_id, repay_amount)print(bill_info)

log_path=db_handler.db_handler(settings.LOG_DATABASE)

bill_log="%s/%s.bills" %(log_path,account_data["account_id"])

with open(bill_log,'a+') as f:

f.write("bill_date: %s account_id: %s need_repay: %d\n" %(year_month, account_id, repay_amount))defget_all_bill():

db_path=db_handler.db_handler(settings.DATABASE)for root, dirs , files inos.walk(db_path):for file infiles:#分割出來結尾的文件

if os.path.splitext(file)[1] =='json':

account_id=os.path.splitext(file)[0] #賬戶id

#檢查這個賬戶

account_data=auth.acc_check(account_id)

status=account_data['status']print("Account bill:".center(50,'='))#除了管理員其他人都應該出賬單

if status !=8:

disp_account_info(account_data)#顯示賬戶詳情

get_bill(account_id)print("End".center(50,'-'))returnTruedefchenk_admin(func):'''檢查是否是管理員

:param func:

:return:'''

def inner(*args,**kwargs):if user_data['account_data'].get('status',None)==8:

ret=func(*args,**kwargs)returnretelse:print("不是管理員")returninnerdefmanage_func(acc_data):'''管理員功能

:param acc_data:

:return:'''menu= u'''------- Admin erea ---------\033[32;1m

1. 添加賬戶

2. 查詢用戶信息

3. 用戶信息修改(凍結帳戶、用戶信用卡額度等)

4. 生成全部用戶帳單

5. 退出

\033[0m'''menu_dic={'1':'auth.sign_up()','2':'account_info(acc_data)','3':'auth.modify()','4':'get_all_bill()','5':'logout(acc_data)',

}

go_flag=Truewhilego_flag:print(menu)

user_option=input(":>>").strip()if user_option inmenu_dic.keys():

go_flag=eval(menu_dic[user_option])else:print("\033[31;1mOption does not exist!\033[0m")defrun():'''這個是普通用戶運行的界面

:return:'''

print("Welocome to ATM".center(50,'#'))

user_data=get_user_data()

interactive(user_data)defadmin_run():print("ATM admin manager".center(50,'#'))

user_data=get_user_data()

manage_func(user_data)

View Code

admin_user.py

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

importosimportsys

base_dir= os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.append(base_dir)from core importmainif __name__ == '__main__':

main.admin_run()#管理員賬戶 admin 密碼 abc

View Code

atm_user.py

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

importosimportsys

base_dir= os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.append(base_dir)from core importmainif __name__ == '__main__':

main.run()#普通用戶 liang 密碼 123456

View Code

文件的存儲位置如以下圖片:

測試如下:

C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python36.exe G:/python/ATM2/bin/atm_user.py

#################Welocome to ATM #################

請輸入用戶名:liang

請輸入密碼123456

----------- user bank ------------

1. 賬戶信息

2. 還款

3. 取款

4. 轉賬

5. 存款

6. 賬單

7. 退出

:>>>1

enroll_date :2018-01-31

id :liang

credit :15000

balance :1888888888737010.2

status :0

expire_date :2023-01-30

pay_day :22

----------- user bank ------------

1. 賬戶信息

2. 還款

3. 取款

4. 轉賬

5. 存款

6. 賬單

7. 退出

:>>>2

{'account_id': 'liang', 'is_authenticated': True, 'account_data': {'enroll_date': '2018-01-31', 'password': '123456', 'id': 'liang', 'credit': 15000, 'balance': 1888888888737010.2, 'status': 0, 'expire_date': '2023-01-30', 'pay_day': 22}}

-------- balance info ---------

Credit : 15000

Balance: 1888888888737010.2

按b退出

請輸入你還款的金額:>>10

2018-01-31 15:41:35,310 - transaction - INFO - account:liang action:repay amount:10.0 interest:0.0

你的余額為1888888888737020.2

按b退出

請輸入你還款的金額:>>b

----------- user bank ------------

1. 賬戶信息

2. 還款

3. 取款

4. 轉賬

5. 存款

6. 賬單

7. 退出

:>>>4

-------- balance info ---------

Credit : 15000

Balance: 1888888888737020.2

輸入你需要轉錢的用戶:>>>>admin

8

不能轉為其他人

輸入你需要轉錢的用戶:>>>>liang

不能轉給自己

輸入你需要轉錢的用戶:>>>>liang2

0

輸入你需要轉的金額:>>1000

2018-01-31 15:42:21,639 - transaction - INFO - account:liang action:transfer amount:1000.0 interest:50.0

2018-01-31 15:42:21,639 - transaction - INFO - account:liang2 action:receive amount:1000.0 interest:0.0

轉錢成功!!!

輸入你需要轉錢的用戶:>>>>

總結

以上是生活随笔為你收集整理的python atm作业详解_python day4 作业 ATM的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。