Python-based network programming for credit card systems that support shopping, transfer, access to money, and timed interest calculation

Source: Internet
Author: User

first, the requirements

second, the idea

1. Buy a shopping category

Credit cards that receive credit cards can have available balances,

Return consumption amount

2. Credit Card (ATM) class

After receiving the last operation, credit card Available Balance, total arrears, remaining arrears, deposit

Where: 1. Each type of transaction does not handle money alone, nor does it record journal separately, each transaction type calls the function that processes the money (incoming transaction type, transaction amount)
2. Functions for handling money, calling the configuration file for the plus and minus money and interest rates for each type of transaction

Return the credit card Available Balance after this operation, total arrears, remaining arrears, deposit

3. Client

Bank Administrator Registration Login
Regular User Registration Login
Send demand: Registration, login, transaction type, transaction amount

4. Server-side

Call shopping class, create shopping object (shopping interface)
Call credit card (ATM) classes, process payments, transfer operations, record interest on monthly basis, write files

5. Scheduled Tasks

Execute the program regularly to calculate interest.

third, the code

3.1 Configuration Files
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 public class

3.2.1 Shopping Category

Class Buy:goods=[{"name": "Computer", "Price": 1999}, {"name": "Mouse", "Price": ten}, {"Name" : "Yacht", "Price": +}, {"name": "Beauty", "Price": 998},] def __init__ (Self,money,consumption,shopping_ca RT,): Self.money=money self.consumption=consumption self.shopping_cart=shopping_cart def gouwu (SE LF): #购物模块 print (' Your current balance is:%d '%self.money) num=int (Input (' Please enter the item number: ') num-=1 if Self.goods[num ["Name"] in Self.shopping_cart.keys (): #goods [num]["name"] Take the product name Self.shopping_cart[self.goods[num ["Name"]][' n ']+=1 #商品数量 +1 else:self.shopping_cart[self.goods[num]["name"]]={"price": SE lf.goods[num]["Price"], ' n ': 1,} # Create shopping cart Dictionary {keys{"prices": Cost, Quantity: 1}} self.money-=self.shopping_cart[self.goods[num][ "Name"]]["Price"]*self.shopping_cart[self.goods[num]["name"]][' n '] #单价 * Quantity Self.consumption+=self.shopping_car t[self.goods[num]["Name"]]["Price"]*self.shopping_cart[self.goods[num]["name"]][' n '] def Yichu (self): #移除购物车模块 c=int (Input (' Please enter 0/1 to select if Remove Cart Item, remove Please enter 1: ')) if C==1:e=int (input (' Please enter the item number to be removed: ')) 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.consumpti On=self.consumption-self.goods[self.goods.index (d) ["Price"] #消费总额减少 else:print (' goods not present ') de F Chongzhi (self): #充值模块 pay=int (Input (' Please enter recharge amount ') self.money=self.money+pay print (' Your current balance is:%d ' sel F.money) #显示当前余额 def main (self): print (' merchandise list: ') for m,n in Enumerate (self.goods,1): Print (m ) for V in N.values (): print (v) print (' ============= ') #消费总额清零 Self.con Sumption=0 BUY=TRUE #定义默认一直购物 while buy:price=0 #定义初始价格 b=1 #定义默认不退出购物或充值状态 if self.money>=p Rice: #消费模块; When the money is greater than the price of the goods, you can start shopping while Self.money>=price: #计价模块, Money will always go shopping s                        Elf.gouwu () #移除购物车商品模块 Self.yichu () if self.money>=0:                        Print (' Your current balance is:%d '%self.money) #显示当前余额 b=int (Input (' Please enter 0/1 to choose whether to continue shopping, please enter 1: '))                    If b==0: # break #退出计价模块 if b==0: #如果不购物          Break #不购物退出整个购物程序 #充值模块 Else:while Self.money<price:                        #金钱不足, can be charged multiple times until you can afford to buy goods a=int ("Your balance is insufficient, please enter 0/1 to choose whether to recharge, recharge Please enter 1: ')") if A==1:                    Self.chongzhi () Else:break #退出充值模块              If a==0:          Break #不充值退出程序 #打印购物车商品名, price of goods, total consumption, balance print (' Your consumption list: ') for m,n in Self.shopping_ Cart.items (): Print (m,n[' price '],n[' n ') #打印消费清单 print (' ============= ') pr Int (' Your current balance is:%d, your total consumption is:%d '% (self.money,self.consumption)) #打印消费总额 return self.consumption

3.2.2 Credit Card ATM class

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_de Bt=remaining_debt #剩余欠款 self.interest=interest #手续费 self.saving=saving #存款 Self.now_time=tim E.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_tim E.tm_mon) +1) def account_info (self): #打印账户信息 return ' account id%s credit card limit%s, credit card available amount%s; remaining arrears%s; '% ( SELF.ID,SELF.CREDIT,SELF.BALANCE,SELF.REMAINING_DEBT,) def ret_account_info (self): return [self.id,self.credit,s Elf.balance,self.debt,self.remaining_debt,self.interest] def repay (self,amount): #还款 Self.handel_money (' repay ', am Ount) def withdraw (self,amount): #取现 selF.handel_money (' withdraw ', amount) def transfer (Self,amount): #转账 Self.handel_money (' transfer ', amount) def con Sume (self,amount): #消费 Self.handel_money (' consume ', amount) def saves (Self,amount): Self.handel_money (' sa            Ving Tsun ', 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_de Bt-=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_de Bt+=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_de Bt,self.interest,self.saving,] #更新基本信息 path_name_base=os.path.join (MULU,STR (self.id) + ' name_base ') pickle . Dump (S,open (path_name_base, ' WB '))
#!/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): "Encrypt password:p aram pwd: Password: return:" Hash=hashlib.md5 (bytes (' xx7 ', encoding= ' Utf-8 ')) hash.update (bytes (pwd,encoding= ' utf-8 ')) return hash.hexd Igest () def login (self,usrname,pwd,x): "Login:p Aram usrname: User name:p aram pwd: Password: RE Turn: Whether to log in successfully ' ' 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): "Registered:p Aram Usrname: username:p Aram P WD: Password: Return: Registration successful ' conn=self.request if x== ' 1 ': Mulu=os.path.join (SETTINGS.A Dmin,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 ') pic Kle.dump (S,open (path_name_pwd, ' WB ') path_name_base=os.path.join (mulu,usrname+ ' name_base ') pickle.du            MP ([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): "Judge Register and login, and display user's detailed directory information, support CD and ls command: return: ' C Onn=self.request if ret== ' 1 ': R=self.login (usrname,pwd,x) if R:conn.sendall (b Ytes (' 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: #用户 Register 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 (continue) Elif ret[0]==1 or Ret[0]==2:break #默认值已更改, the bank administrator has operated if Ret[0]==1: #如果管理员同 Italian 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.se            Ndall (bytes (' n ', encoding= ' Utf-8 ')) def Interactive (self,usrname): #进行交互 conn=self.request while True: C=CONN.RECV (1024x768) #接收用户交互选项 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_nam E_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,enco                ding= ' 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.rec V (1024x768) 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 (' Received User class ', encoding= ' Utf-8 ')) while True:if x== ' 1 ' or x== ' 2 ': B=conn.recv (1024x768) ret=str (b,encoding= ' utf-8 ') Conn.sendall (byt Es (' b ok ', encoding= ' Utf-8 ')) C=conn.recv (1024x768) r=str (c,encoding= ' utf-8 ') USRN  Ame,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 client
#!/usr/bin/env python#-*-coding:utf-8-*-"" This program as a user or bank administrator of the portal, where c=1 on behalf of the Bank administrator, c=2 on behalf of ordinary users ' "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): "Login:p Aram Usrname: username:p Aram PWD : Password: Return: Whether the login succeeded ' ' Obj.sendall (bytes (usrname+ ', ' +pwd,encoding= ' Utf-8 ')) Ret=obj.recv (1024x768) r=str (ret,en coding= ' Utf-8 ') if r== ' y ': return 1 Else:return 0def regist (usrname,pwd,x): ' Register:p Aram US Rname: Username:p aram pwd: Password: return: Registration successful ' Obj.sendall (bytes (usrname+ ', ' +pwd,encoding= ' Utf-8 ')) Ret=obj.rec V (1024x768) r=str (ret,encoding= ' utf-8 ') if r== ' y ': return 1 Else:return 0def User_identity_authenticat Ion (USRNAME,PWD,X): "Select login or register, display user's detailed directory information, support CD and ls command: return: ' A=input (' Please select 1. Login 2. Register ') Obj.sendall (b  Ytes (a,encoding= ' utf-8 ')) OBJ.RECV (1024)  If a== ' 1 ': Ret=login (USRNAME,PWD) if Ret:print (' login successful ') return 1 else: Print (' Username or password error ') return 0 elif a== ' 2 ': ret=regist (usrname,pwd,x) if Ret:prin T (' registered success ') return 1 else:print (' User name already exists or bank administrator refused ') return 0def main (x): Usrname=i Nput (' Enter user name ') pwd=input (' Please enter password ') if User_identity_authentication (usrname,pwd,x): #如果验证身份成功 if x== ' 1 ': #处理用 User registration information while true:s=pickle.load (open (settings. A, ' RB ')) if S[1]==0:time.sleep (continue elif s[1]                            ==1:while true:a=input (' User request registration, Input 1 agree, 2 reject ') 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 (' input error ')  Break Else: #普通用户登陆后 Interactive () #进行交互def Interactive (): While True:a=input (' Please select 1. Repayment 2. Withdrawal 3. Transfer 4. Consumption 5. Deposit Q exit ') Obj.sendall (bytes (a,encoding= ' utf-8 ')) R=obj.recv (1024x768) #接收账户信息 ret= Str (r,encoding= ' utf-8 ') print (ret) if a! = ' 4 ' and a! = ' Q ': B=input (' Please enter amount ') 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 (' Please select 1. Bank Administrator 2. User q, Exit ') Obj.sendall (bytes (x,encoding= ' utf-8 ')) Obj.recv (1024x768) #确认收到 User class if x== ' 1 ' or x== ' 2 ': Main (x) break elif x== ' Q ': Break else:print (' input wrong Please reenter ') OB J.close ()
#!/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 () # Recurring Bill list for monthly arrears. and write to the current month's bill for item in basic_info[' debt ': interest = item[' total_debt '] * 0.0005 if Basic_inf O[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 ')) # if current equals 10th (before 9th) # The current balance is negative, add the value to the billing list and start the interest rate, which is available this month        Quota recovery. Date = Time.strftime ("%y-%m-%d ") if struct_time.tm_mday = = one and Basic_info[2]>0:dic = {' Date ': Date," Total_debt ": basic_info[2]," BALANCE_DEBT ": Basic_info[2],} basic_info[1] . Append (DIC) # Recovery available amount Basic_info[0] = 15000 Pickle.dump (basic_info, op En (Os.path.join (settings). All_users, card, card+ ' name_base '), ' W ') def Run (): Main ()

  

  

Python-based network programming for credit card systems that support shopping, transfer, access to money, and timed interest calculation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.