Python實現信用卡系統(支援購物、轉賬、存取錢),python信用卡
最近一直在做一個有關信用卡系統的項目,所有很少出來給大家打招呼了,今天也該告一段了,本項目是基於python程式設計語言做的,此信用卡支援購物,轉賬和存取錢,下面小編把需求及實現思路大概分享一下,僅供參考,如有bug歡迎各位大俠提出,共同學習進步,謝謝!
一、要求
二、思路
1.購物類buy
接收 信用卡類 的信用卡可用可用餘額,
返回消費金額
2.信用卡(ATM)類
接收上次操作後,信用卡可用餘額,總欠款,剩餘欠款,存款
其中: 1.每種交易類型不單獨處理金錢,也不單獨記錄流水賬,每種交易類型調用處理金錢的函數(傳入交易類型,交易金額)
2.處理金錢的函數,調用設定檔中關於每種交易類型的加減錢和利率
返回本次操作後信用卡可用餘額,總欠款,剩餘欠款,存款
3.用戶端
銀行管理員註冊登陸
普通使用者註冊登陸
發送需求:註冊、登陸、交易類型、交易金額
4.伺服器端
調用購物類,建立購物對象(購物介面)
調用信用卡(ATM)類,處理還款,轉賬等操作,對利息按月記錄,寫入檔案
5.定時任務
定時執行程式,以計算利息。
三、代碼
3.1設定檔
import osBASE_DIR = os.path.dirname(os.path.dirname(__file__)) #設定檔的上層目錄DB_DIR=os.path.join(BASE_DIR,'db') #資料檔案夾ADMIN=os.path.join(DB_DIR,'admin')ALL_USERS=os.path.join(DB_DIR,'allusrs')A=os.path.join(BASE_DIR,'db','s')LOG=os.path.join(BASE_DIR,'log')TRANSACTION={ 'repay':{'action':'plus','interest':0}, #還款 'withdraw':{'action':'minus','interest':0.05},#取現 'transfer':{'action':'minus','interest':0.05},#轉賬 'consume':{'action':'minus','interest':0},#消費 'saving':{'action':'plus','interest':0} #存款}
3.2公用類
3.2.1購物類
class buy: goods=[ {"name": "電腦", "price": 1999}, {"name": "滑鼠", "price": 10}, {"name": "遊艇", "price": 20}, {"name": "美女", "price": 998}, ] def __init__(self,money,consumption,shopping_cart,): self.money=money self.consumption=consumption self.shopping_cart=shopping_cart def gouwu(self): #購物模組 print('您的當前餘額為:%d' %self.money) num=int(input('請輸入商品序號:')) num-=1 if self.goods[num]["name"] in self.shopping_cart.keys(): #goods[num]["name"]取商品名 self.shopping_cart[self.goods[num]["name"]]['n']+=1 #商品數量+1 else: self.shopping_cart[self.goods[num]["name"]]={"price":self.goods[num]["price"],'n':1,} # 建立購物車字典 {keys{"price":價格,數量:1}} self.money-=self.shopping_cart[self.goods[num]["name"]]["price"]*self.shopping_cart[self.goods[num]["name"]]['n'] #單價*數量 self.consumption+=self.shopping_cart[self.goods[num]["name"]]["price"]*self.shopping_cart[self.goods[num]["name"]]['n'] def yichu(self): #移除購物車模組 c=int(input(' 請輸入0/1選擇是否移除購物車商品, 移除請輸入1:')) if c==1: e=int(input(' 請輸入要移除的商品序號:')) d=self.goods[e-1] if d in self.shopping_cart.keys(): #判斷要移除的商品是否在購物車內 self.shopping_cart.remove(d) #移除商品 self.money=self.money+self.goods[self.goods.index(d)]["price"] #餘額增加 self.consumption=self.consumption-self.goods[self.goods.index(d)]["price"] #消費總額減少 else: print('商品不存在') def chongzhi(self): #儲值模組 pay=int(input('請輸入儲值金額')) self.money=self.money+pay print('您的當前餘額為:%d' % self.money) #顯示當前餘額 def main(self): print('商品清單:') for m,n in enumerate(self.goods,1): print(m) for v in n.values(): print(v) print('=============') #消費總額清零 self.consumption=0 buy=True #定義預設一直購物 while buy: price=0 #定義初始價格 b=1 #定義預設不退出購物或儲值狀態 if self.money>=price: #消費模組;金錢大於貨物價格時,才能開始購物 while self.money>=price: #計價模組,有錢就可以一直購物 self.gouwu() #移除購物車商品模組 self.yichu() if self.money>=0: print('您的當前餘額為:%d' %self.money) #顯示當前餘額 b=int(input(' 請輸入0/1選擇是否繼續購物, 購物請輸入1:')) if b==0: # break #退出計價模組 if b==0: #如果不購物 break #不購物退出整個購物程式 #儲值模組 else: while self.money<price: #金錢不足,可多次充錢,直到能買得起貨物 a=int(input(' 您的餘額不足,請輸入0/1選擇是否儲值,儲值請輸入1:')) if a==1: self.chongzhi() else: break #退出儲值模組 if a==0: break #不儲值退出程式 #列印購物車商品名、商品價格、消費總額、餘額 print('您的消費清單為:') for m,n in self.shopping_cart.items(): print(m,n['price'],n['n']) #列印消費清單 print('=============') print('您的當前餘額為:%d,您的消費總額為:%d' % (self.money,self.consumption) ) #列印消費總額 return self.consumption
3.2.2 信用卡ATM類
class Atm: credit=15000 #信用卡額度 def __init__(self,balance,debt,remaining_debt,interest,saving,id): self.id=id #信用卡id self.balance=balance #信用卡可用金額 self.debt=debt #總欠款 self.remaining_debt=remaining_debt #剩餘欠款 self.interest=interest #手續約 self.saving=saving #存款 self.now_time=time.strftime("%Y-%m-%d %H:%M:%S") self.now_data=time.strftime("%Y-%m") self.struct_time=time.gmtime(time.time()) if self.struct_time.tm_mday>22: self.now_data=self.struct_time.tm_year+'-'+str(int(self.struct_time.tm_mon)+1) def account_info(self):#列印賬戶資訊 return '賬戶id%s 信用卡額度%s;信用卡可用金額%s;剩餘欠款%s;'%(self.id,self.credit,self.balance,self.remaining_debt,) def ret_account_info(self): return [self.id,self.credit,self.balance,self.debt,self.remaining_debt,self.interest] def repay(self,amount):#還款 self.handel_money('repay',amount) def withdraw(self,amount): #取現 self.handel_money('withdraw',amount) def transfer(self,amount): #轉賬 self.handel_money('transfer',amount) def consume(self,amount): #消費 self.handel_money('consume',amount) def saves(self,amount): self.handel_money('saving',amount) def transaction(self,a,amount): dic={ '1':self.repay, '2':self.withdraw, '3':self.transfer, '4':self.consume, '5':self.saves } print("debug: a:",type(a),"amount:",type(amount)) print(a) print(dic[a]) print(dic["5"]) dic[a](amount) print("end debug") def handel_money(self,transaction,amount): #交易類型, amount=int(amount) interest=amount*settings.TRANSACTION[transaction]['interest'] #手續約計算 if settings.TRANSACTION[transaction]['action']=='plus': if amount<=self.remaining_debt: self.remaining_debt-=amount self.balance+=amount else: self.balance+=self.remaining_debt self.remaining_debt=0 self.saving+=amount-self.remaining_debt else: if self.saving<amount: self.saving=0 a=amount-self.saving self.balance-=a+interest-self.saving # self.debt+=amount+interest self.remaining_debt+=a+interest a='time:%s id:%s transaction: %s amount:%s interest %s \n'%(self.now_time,self.id,transaction,amount,interest) print(a) mulu=os.path.join(settings.ALL_USERS,self.id) path_name_liushui=os.path.join(mulu,str(self.id)+'name_liushui',str(self.now_data)) with open(path_name_liushui,'a')as f: #記錄流水資訊 f.write(a) s=[self.balance,self.debt,self.remaining_debt,self.interest,self.saving,] #更新基本資料 path_name_base=os.path.join(mulu,str(self.id)+'name_base') pickle.dump(s,open(path_name_base,'wb'))
3.3伺服器端:
#!/usr/bin/env python# -*- coding: utf-8 -*-import sys,osimport hashlibimport pickleimport timeimport socketserversys.path.append(os.path.dirname(os.path.dirname(__file__)))from config import settingsfrom lib import modulesfrom lib.modules import *class Myserver(socketserver.BaseRequestHandler): def md5(self,pwd): ''' 對密碼進行加密 :param pwd: 密碼 :return: ''' hash=hashlib.md5(bytes('xx7',encoding='utf-8')) hash.update(bytes(pwd,encoding='utf-8')) return hash.hexdigest() def login(self,usrname,pwd,x): ''' 登陸 :param usrname: 使用者名稱 :param pwd: 密碼 :return:是否登陸成功 ''' conn=self.request if x=='1': path_name_pwd=os.path.join(settings.ADMIN,usrname) else: mulu=os.path.join(settings.ALL_USERS,usrname) path_name_pwd=os.path.join(mulu,usrname+'name_pwd') s=pickle.load(open(path_name_pwd,'rb')) if usrname in s: if s[usrname]==self.md5(pwd): #和加密後的密碼進行比較 return True else: return False else: return False def regist(self,usrname,pwd,x): ''' 註冊 :param usrname: 使用者名稱 :param pwd: 密碼 :return:是否註冊成功 ''' conn=self.request if x=='1': mulu=os.path.join(settings.ADMIN,usrname) else: mulu=os.path.join(settings.ALL_USERS,usrname) if os.path.exists(mulu): return False else: os.mkdir(mulu) s={} s[usrname]=self.md5(pwd) path_name_pwd=os.path.join(mulu,usrname+'name_pwd') pickle.dump(s,open(path_name_pwd,'wb')) path_name_base=os.path.join(mulu,usrname+'name_base') pickle.dump([15000,{},0,0,0],open(path_name_base,'wb')) path_name_liushui=os.path.join(mulu,usrname+'name_liushui') os.mkdir(path_name_liushui) return True def user_identity_authentication(self,usrname,pwd,ret,x): ''' 判斷註冊和登陸,並展示使用者的詳細目錄資訊,支援cd和ls命令 :return: ''' conn=self.request if ret=='1': r=self.login(usrname,pwd,x) if r: conn.sendall(bytes('y',encoding='utf-8')) else: conn.sendall(bytes('n',encoding='utf-8')) elif ret=='2': # print(usrname,pwd) if x=='1': r=self.regist(usrname,pwd,x) else: #使用者註冊 s=[0,1] pickle.dump(s,open(settings.A,'wb')) while True: ret=pickle.load(open(settings.A,'rb')) if ret[0]==0: time.sleep(30) continue elif ret[0]==1 or ret[0]==2: break #預設值已更改,銀行管理員已操作 if ret[0]==1: #如果管理員同意 r=self.regist(usrname,pwd,x) else: r=0 s=[0,0] pickle.dump(s,open(settings.A,'wb')) if r: conn.sendall(bytes('y',encoding='utf-8')) else: conn.sendall(bytes('n',encoding='utf-8')) def interactive(self,usrname): #進行互動 conn=self.request while True: c=conn.recv(1024) #接收使用者互動選項 r=str(c,encoding='utf-8') mulu=os.path.join(settings.ALL_USERS,usrname) path_name_base=os.path.join(mulu,usrname+'name_base') s=pickle.load(open(path_name_base,'rb')) #列印賬戶資訊 obj=modules.Atm(s[0],s[1],s[2],s[3],s[4],usrname) #Atm對象 a=obj.account_info() #接收賬戶資訊 conn.sendall(bytes(a,encoding='utf-8')) b=obj.ret_account_info() if r== '4': buy_obj=modules.buy(b[2],0,{}) amount=buy_obj.main() elif r=='q': break else: s=conn.recv(1024) amount=str(s,encoding='utf-8') obj.transaction(r,amount) pass def handle(self): conn=self.request x=conn.recv(1024) x=str(x,encoding='utf-8') conn.sendall(bytes('收到使用者類別',encoding='utf-8')) while True: if x=='1' or x=='2': b=conn.recv(1024) ret=str(b,encoding='utf-8') conn.sendall(bytes('b ok',encoding='utf-8')) c=conn.recv(1024) r=str(c,encoding='utf-8') usrname,pwd=r.split(',') print(usrname,pwd) self.user_identity_authentication(usrname,pwd,ret,x) #登陸或註冊驗證 if x=='2':#普通使用者身分識別驗證成功後 self.interactive(usrname) pass break elif x=='q': breakif __name__=='__main__': sever=socketserver.ThreadingTCPServer(('127.0.0.1',9999),Myserver) sever.serve_forever()
3.4 使用者端
#!/usr/bin/env python# -*- coding: utf-8 -*-'''本程式作為使用者或銀行管理員的入口,其中c=1代表銀行管理員,c=2代表普通使用者'''import pickleimport sysimport timeimport osimport socketsys.path.append(os.path.dirname(os.path.dirname(__file__)))from config import settingsfrom lib import *from lib.modules import *def login(usrname,pwd): ''' 登陸 :param usrname:使用者名稱 :param pwd:密碼 :return:是否登陸成功 ''' obj.sendall(bytes(usrname+','+pwd,encoding='utf-8')) ret=obj.recv(1024) r=str(ret,encoding='utf-8') if r=='y': return 1 else: return 0def regist(usrname,pwd,x): ''' 註冊 :param usrname:使用者名稱 :param pwd:密碼 :return:是否註冊成功 ''' obj.sendall(bytes(usrname+','+pwd,encoding='utf-8')) ret=obj.recv(1024) r=str(ret,encoding='utf-8') if r=='y': return 1 else: return 0def user_identity_authentication(usrname,pwd,x): ''' 選擇登陸或註冊,展示使用者的詳細目錄資訊,支援cd和ls命令 :return: ''' a=input('請選擇1.登陸 2.註冊') obj.sendall(bytes(a,encoding='utf-8')) obj.recv(1024) if a=='1': ret=login(usrname,pwd) if ret: print('登陸成功') return 1 else: print('使用者名稱或密碼錯誤') return 0 elif a=='2': ret=regist(usrname,pwd,x) if ret: print('註冊成功') return 1 else: print('使用者名稱已存在或銀行管理員拒絕') return 0def main(x): usrname=input('請輸入使用者名稱') pwd=input('請輸入密碼') if user_identity_authentication(usrname,pwd,x): #如果驗證身份成功 if x=='1': #處理使用者註冊資訊 while True: s=pickle.load(open(settings.A,'rb')) if s[1]==0: time.sleep(30) continue elif s[1]==1: while True: a=input('使用者請求註冊,輸入1同意,2拒絕') if a=='1': s=[1,0] pickle.dump(s,open(settings.A,'wb')) break elif a=='2': s=[2,0] pickle.dump(s,open(settings.A,'wb')) break else: print('輸入有誤') break else: #普通使用者登陸後 interactive() #進行互動def interactive(): while True: a=input('請選擇 1.還款 2.取現 3.轉賬 4.消費 5.存錢 q退出') obj.sendall(bytes(a,encoding='utf-8')) r=obj.recv(1024) #接收賬戶資訊 ret=str(r,encoding='utf-8') print(ret) if a !='4'and a !='q': b=input('請輸入金額') obj.sendall(bytes(b,encoding='utf-8')) elif a=='q': breakobj=socket.socket() #建立用戶端socket對象obj.connect(('127.0.0.1',9999))while True: x=input('請選擇1.銀行管理員 2.使用者 q、退出') obj.sendall(bytes(x,encoding='utf-8')) obj.recv(1024) #確認收到使用者類別 if x=='1' or x=='2': main(x) break elif x=='q': break else: print('輸入有誤請重新輸入')obj.close()
3.5定時任務
#!/usr/bin/env python# -*- coding:utf-8 -*-import os,sysimport json,pickleimport timesys.path.append(os.path.dirname(os.path.dirname(__file__)))from config import settingsdef main(): card_list = os.listdir(settings.ALL_USERS) for card in card_list: basic_info = pickle.load(open(os.path.join(settings.ALL_USERS, card, card+'name_base'))) struct_time = time.localtime() # 迴圈賬單列表,為每月的欠款計息。並寫入到當月賬單中 for item in basic_info['debt']: interest = item['total_debt'] * 0.0005 if basic_info[4] >= interest: basic_info[4] -= interest else: temp = interest - basic_info[4] basic_info[4]=0 basic_info[0] -= temp pickle.dump( basic_info, open(os.path.join(settings.ALL_USERS, card, card+'name_base'),'w') ) # 如果當前等於10號(9號之前) # 當前餘額為負值,則將值添加到賬單列表中,開始計息,同時,本月可用額度恢複。 date = time.strftime("%Y-%m-%d") if struct_time.tm_mday == 11 and basic_info[2]>0: dic = {'date': date, "total_debt": basic_info[2], "balance_debt": basic_info[2], } basic_info[1].append(dic) # 恢複可用額度 basic_info[0] = 15000 pickle.dump( basic_info, open(os.path.join(settings.ALL_USERS, card, card+'name_base'),'w') )def run(): main()
以上所述是小編給大家介紹的Python實現信用卡系統(支援購物、轉賬、存取錢)的全部內容,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!