Python implements credit card systems such as online mall, money transfer, access, and other functions _python

Source: Internet
Author: User
Tags md5 mkdir sleep

I. Requirements

Second, train of thought

1. Shopping class Buy

Receive credit card class credit card available balances,

Return consumption amount

2. Credit card (ATM) class

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

of which: 1. Each transaction type does not deal with money separately, nor does it record chronological, each transaction type invokes a function that handles money (incoming transaction type, transaction amount)

2. A function that deals with money, invoking the addition and reduction of money and interest rates for each transaction type in the configuration file

Return credit card available after this operation balance, total arrears, remaining arrears, deposit

3. Client

Bank administrator registered to login

Normal 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) class, process repayment, transfer and other operations, monthly record of interest, write to file

5. Timed Tasks

Timed execution of the program 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 ')  #数据文件夹
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 Classes

3.2.1 Shopping Class

Class Buy:goods=[{"name": "Computer", "Price": 1999}, {"name": "Mouse", "price": {"name": "Yacht", "Price": 20}, {"Name": "Beauty", "Price": 998},] def __init__ (Self,money,consumption,shopping_cart,): Self.money=money self.consum Ption=consumption Self.shopping_cart=shopping_cart def Gouwu (self): #购物模块 print (' Your current balance is:%d '%self.money) num=int (Input (' Please enter product serial number: ')] num-=1 if self.goods[num]["name" in Self.shopping_cart.keys (): #goods [num][' name] ' to take commodity 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,} # Create shopping cart Dictionary {keys{" prices ": Rates, 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_cart [self.goods[num][' name ']] ["Price"]*self.shopping_cart[self.goods[num]["name"]][' n '] def Yichu (self): #移除购物车模块 c=int (' Enter 0/
1 Choose whether to remove the shopping cart merchandise, remove Please enter 1: ')  If C==1:e=int (enter the item 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 does not exist ') def Chongz Hi (self): #充值模块 pay=int (Input (' Please enter Recharge amount ')) Self.money=self.money+pay print (' Your current balance is:%d '% Self.money) #显示当前余额 def Main (self): print (' Product list: ') for m,n in Enumerate (self.goods,1): Print (m) for V in N.values (): Print (v) PRI NT (' ============= ') #消费总额清零 self.consumption=0 buy=true #定义默认一直购物 while buy:price=0 #定义初始价格 b=1 #定义默认不退出购物或 Recharge status if Self.money>=price: #消费模块; When money is greater than the price of goods, you can start shopping while Self.money>=price: #计价模块, you can always shop with money Self.go Uwu () #移除购物车商品模块 Self.yichu () if Self.money>=0:print (' Your current balance is:%d '%self.money) #显示当前余额 b=int (' Please enter 0/1 to choose whether to continue shopping, For shopping Please enter 1: ') if b==0: # break #退出计价模块 if b==0: #如果不购物 break #不购物退出整个购物程序 #充值模块 ELSE:WH Ile Self.money<price: #金钱不足, can be charged many times, until can afford the 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 #不充值退出程序 #打印购物车商品名, commodity prices, total consumption, balance print (' Your consumption list is: ') for M,n in Self.shopping_cart.items (): Print (m,n[' price '],n[' n ')) #打印消费清单 print (' ============= ') print (' 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 #信用卡i D self.balance=balance #信用卡可用金额 self.debt=debt #总欠款 self.remaining_debt=remaining_debt #剩余欠款 self.interest=inte Rest #手续费 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.t m_year+ '-' +str (int (Self.struct_time.tm_mon) +1) def account_info (self): #打印账户信息 return ' account id%s credit card amount%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.hand El_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.cons Ume, ' 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) inte Rest=amount*settings. transaction[transaction][' interest '] #手续费计算 if settings. transaction[transaction][' action ']== ' plus ': if Amount<=self.remaining_debt:self.remaining_debt-=amount se Lf.balance+=amount else:self.balance+=self.remaining_debt self.remaining_debt=0 SELF.SAVING+=AMOUNT-SELF.R Emaining_debt else:if self.saving<amount:self.saving=0 a=amount-self.saving self.balance-=a+intere St-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.s Aving,] #更新基本信息 path_name_base=os.path.join (MULU,STR (self.id) + ' name_base ') pickle.dump (S,open (path_name_base, ' WB ') ))

3.3 Server-side:

#!/usr/bin/env python #-*-coding:utf-8-*-import sys,os import hashlib import pickle import time Import Socketserve R Sys.path.append (Os.path.dirname (Os.path.dirname (__file__)) from config Import settings from Lib import modules from Li B.modules Import * Class Myserver (socketserver. Baserequesthandler): def MD5 (SELF,PWD): ' Encrypt password:p aram pwd: Password: return: ' Hash=hashlib.md5 (' bytes ', encoding= ' 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 succeeded ' 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 pwd: Password: return: Register Success ' 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.md 5 (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_authe Ntication (self,usrname,pwd,ret,x): "' Judge registration and login, and display user's detailed catalog information, support CD and ls command: 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,pwdIf x== ' 1 ': r=self.regist (usrname,pwd,x) Else: #用户注册 s=[0,1] Pickle.dump (settings. A, ' WB ') while True:ret=pickle.load (open settings. A, ' RB ') if Ret[0]==0:time.sleep (A) Continue elif ret[0]==1 or Ret[0]==2:break #默认值已更改, Bank Management The member 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 ')) de F Interactive (self,usrname): #进行交互 conn=self.request while TRUE:C=CONN.RECV (1024) #接收用户交互选项 r=str (c,encoding= ' u Tf-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): con N=self.request X=CONN.RECV (1024) x=str (x,encoding= ' utf-8 ') conn.sendall (bytes (' Received User class ', encoding= ' Utf-8 ')) while Tr Ue: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 ': Break if __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 procedure serves as a user's or bank administrator's entry, c=1 on behalf of the Bank administrator, c=2 on behalf of ordinary users ' import pickle import sys IM Port time import OS import socket Sys.path.append (Os.path.dirname (Os.path.dirname (__file__)) from config import 
 Settings from Lib Import * from lib.modules import * def login (usrname,pwd): ' Login:p Aram Usrname: Username:p aram pwd: Password : return: Whether to login successfully ' 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 0 def regist (usrname,pwd,x): "' Registered:p Aram Usrname: Username:p aram pwd: Password : return: Whether to register successfully ' 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 0 def user_identity_authentication (usrname,pwd,x): ' Select login or register to display user's detailed catalogue information, branch Hold CD and ls command: return: ' A=input (' Please select 1. Login 2. Registered ') Obj.sendall (bytes (a,encoding= ' utf-8 ')) OBJ.RECV (1024) if a== ' 1 ': RET =login (USRNAME,PWD) if Ret:print (' Login succeeded '] return 1 else:print (' Username or password error ') return 0 elif a== ' 2 ': ret=regist (usrname,pwd,x) if Ret:print ( ' Registered success '] return 1 else:print (' username already exists or Bank admin refused ') return 0 def main (x): Usrname=input (' enter username ') pwd=input (' Please enter your password ') if User_identity_authentication (usrname,pwd,x): #如果验证身份成功 if x== ' 1 ': #处理用户注册信息 while True:s=pickle.load (op En (Settings. A, ' RB ') if S[1]==0:time.sleep (A) Continue elif s[1]==1:while true:a=input (' User request registration, enter 1 consent, 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 interact Ive (): While True:a=input (' Please select 1. Repayment 2.3 Transfer 4. Consumption 5. Save Q Exit ') Obj.sendall (bytes (a,encoding= ' utf-8 ')) R=obj.recv (10 #接收账户信息 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.con Nect (' 127.0.0.1 ', 9999) while True:x=input (' Please select 1. Bank Manager 2. User q, Exit ') 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 (' input error Please re-enter ') Obj.close ()

3.5 timed Tasks

#!/usr/bin/env python #-*-coding:utf-8-*-import os,sys import json,pickle import time Sys.path.append (os.path.dirname
(Os.path.dirname (__file__)) From config import settings def main (): Card_list = Os.listdir (settings. All_users in card_list:basic_info = pickle.load (open os.path.join (settings). All_users, card, card+ ' Name_base ')) Struct_time = Time.localtime () # Circular billing list for monthly arrears.
    and write to the current month's bill for the 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 current equals number 10th (before 9th) # The current balance is negative, add the value to the billing list, start the interest rate, and restore the available amount this month. Date = Time.strftime ("%y-%m-%d") if Struct_time.tm_mday = = Basic_info[2]>0:dic = {' Date ': Date, ' Tota L_debt ": basic_info[2]," BALANCE_DEBT ": Basic_info[2],} basic_info[1].append (DIC) # Restore available amount basic_info[0] = 15000 Pickle.dump (basic_info, Open (Os.path.join, settings.
   All_users, card, card+ ' name_base '), ' W ') def Run (): Main ()

The above is to use Python to develop online shopping card system, students need to refer to.

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.