Python's credit card system for online shopping, money transfer, access and other functions

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 OS Base_dir = Os.path.dirname (Os.path.dirname (__file__)) #配置文件的上层目录DB_DIR =os.path.join (Base_dir, ' db ')  # Data folder 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 ')  

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_cart,): Self.money=money Self.consumption=consu Mption Self.shopping_cart=shopping_cart def Gouwu (self): #购物模块 print (' Your current balance is:%d '%self.money) num=int (Input (' Please enter the product serial number : ')) num-=1 if self.goods[num]["name"] in Self.shopping_cart.keys (): #goods [num]["name"] Take product name Self.shopping_cart[sel f.goods[num]["name"]][' n ']+=1 #商品数量 +1 else:self.shopping_cart[self.goods[num]["name"]]={"Price": self.goods[num][ "Price"], ' n ': 1,} # Create cart dictionary {keys{"prices": Cost, Quantity: 1}} self.money-=self.shopping_cart[self.goods[num]["name"]]["value" ]*self.shopping_cart[self.goods[num]["name"]][' n '] #单价 * Quantity self.consumption+=self.shopping_cart[self.goods[num][" Name "]][" Price "]*self.shopping_cart[self.goods[num][" name "]][' n '] def Yichu (self): #移除购物车模块 c=int (Input (' please enter 0/ 1 Select whether to remove the shopping 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.consumption=self.consumption -self.goods[self.goods.index (d) ["Price"] #消费总额减少 else:print (' Commodity not Present ') def Chongzhi (self): #充值模块 pay=int (Input (' Please enter charge Value amount ') Self.money=self.money+pay print (' Your current balance is:%d '% Self.money) #显示当前余额 def main (self): print (' merchandise list: ') for M,n in E Numerate (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: #消费模块; When money is greater than the price of goods, it can be opened       Start shopping while Self.money>=price: #计价模块, Money can always be shopping self.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: #If you do not shop break #不购物退出整个购物程序 #充值模块 Else:while Self.money 
 
  

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 S Elf.balance=balance #信用卡可用金额 self.debt=debt #总欠款 self.remaining_debt=remaining_debt #剩余欠款 self.interest=interest #手 Renewals 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 ' 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, 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.b Alance+=amount else:self.balance+=self.remaining_debt self.remaining_debt=0 self.saving+=amount-self.remaining _DEBT else:if self.saving

3.3 Server side:

#!/usr/bin/env python#-*-coding:utf-8-*-import sys,osimport hashlibimport pickleimport timeimport SOCKETSERVERSYS.PA Th.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 ', Encodi  ng= ' Utf-8 ')) hash.update (bytes (pwd,encoding= ' utf-8 ')) return hash.hexdigest () def login (self,usrname,pwd,x): "Login :p Aram Usrname: Username:p aram pwd: Password: return: Login successful ' conn=self.request if x== ' 1 ': path_name_pwd=os.path.join (Sett Ings. 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 pwd: Password: return: Registration successful ' 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): "Judge Register and login, and display user's detailed directory information, support CD and ls command: return:" ' Conn=self.request if ret== ' 1 ': R=self.lo Gin (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 (continue elif ret[0]==1 or Ret[0]==2:break #默认值已更改, bank administrator has operated 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 int   Eractive (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_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 ': Brea  K 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 ( 1024x768) 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 (bytes (' B ok ', encoding= ' Utf-8 ')) C=conn.recv (1024x768) r=s TR (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 ': Break if __n ame__== ' __main__ ': Sever=socketserver. Threadingtcpserver ((' 127.0.0.1 ', 9999), Myserver) Sever.serve_forever ()

3.4 User-side

#!/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 succeeds ' ' Obj.sendall (bytes (usrname+ ', ' +pwd,encoding= ' Utf-8 ')) Ret=obj.recv (1024x768) r=str (ret,encoding= ' utf-8 ') if R = = ' Y ': return 1 Else:return 0 def regist (usrname,pwd,x): "Registered:p Aram Usrname: Username:p aram pwd: Password: return: Registration Successful" obj . Sendall (Bytes (usrname+ ', ' +pwd,encoding= ' Utf-8 ')) Ret=obj.recv (1024x768) r=str (ret,encoding= ' utf-8 ') if r== ' y ': return 1 Else:return 0def user_identity_authentication (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 (bytes (a,encoding= ' utf-8 ')) Obj.recv (1024x768) if a== ' 1 ': Ret=login (USRNAME,PWD) if Ret:print ( ' Login successful ') return 1 else:print (' Username or password error ') return 0Elif a== ' 2 ': ret=regist (usrname,pwd,x) if Ret:print (' registration successful ') return 1 else:print (' username already exists or bank administrator refuses ') return 0def Main (x): Usrname=input (' Please enter username ') pwd=input (' Please enter password ') 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 (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 wrong ') break else: #普通用户登陆后 Interactive () #进行交互 def Interactive (): WH  Ile 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 ': Break Obj=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) #确认收到用户类别 if x== ' 1 ' or x== ' 2 ': Main (x) break elif x== ' Q ': Break else:print (' input wrong please re-enter ') Obj.close ()

3.5 Scheduled Tasks

#!/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 settings def 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_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 ')) # If the current balance is equal to 10th (before number 9th) # A negative value is added to the bill list to start the interest, and this month the available amount is restored. Date = Time.strftime ("%y-%m-%d") if struct_time.tm_mday = = one and Basic_info[2]>0:dic = {' Date ': Date, ' Total_d EBT ": basic_info[2]," BALANCE_DEBT ": Basic_info[2],} basic_info[1]. Append (DIC) # Recovery available amount Basic_info[0] = 15000 Pickle.dump (basic_info, open (os.path.join.   All_users, card, card+ ' name_base '), ' W ') def Run (): Main ()

The above is the development of online shopping mall with Python credit card system, the students need to refer to the next.

  • 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.