Python implements the Credit Card System (supports shopping, transfers, and money access) and python credit card

Source: Internet
Author: User

Python implements the Credit Card System (supports shopping, transfers, and money access) and python credit card

Recently, I have been working on a project on the credit card system, and I seldom say hello to anyone. Today, I should have told you that this project is based on the python programming language, this credit card supports shopping, money transfer and money access. The following small series will share your needs and implementation ideas for your reference only. If you have any bugs, you are welcome to raise them and learn and make progress together. Thank you!

I. Requirements


Ii. Ideas

1. Shopping buy

Available credit card balances for receiving credit cards,

Return consumption amount

2. Credit Card (ATM)

After receiving the last operation, the available credit card balance, total amount owed, remaining amount owed, and deposit

Among them: 1. Each transaction type does not process money independently, nor records the sequential account separately. Each transaction type calls the function for processing money (incoming transaction type and transaction amount)

2. The money processing function calls the configuration file to add or subtract money and interest rates for each transaction type.

Return the available credit card balance, total amount owed, remaining amount owed, and deposit after this operation

3. Client

Bank administrator registration Login

Common User Registration and login

Sending requirements: Registration, login, transaction type, transaction amount

4. Server Side

Call the shopping class to create shopping objects (shopping Interface)
Call the credit card (ATM) class, handle the repayment, transfer and other operations, record the interest on a monthly basis, and write the file

5. scheduled tasks

Periodically execute the program to calculate the interest.

Iii. Code

3.1 configuration file

import os
BASE_DIR = os.path.dirname (os.path.dirname (__ file__)) #Upper directory of the configuration 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')
TRANSACTION = {
  'repay': {'action': 'plus', 'interest': 0}, #payment
  'withdraw': {'action': 'minus', 'interest': 0.05}, # 取 Cash
  'transfer': {'action': 'minus', 'interest': 0.05}, # transfer
  'consume': {'action': 'minus', 'interest': 0}, #
  'saving': {'action': 'plus', 'interest': 0} #Deposit
}
3.2 public classes

3.2.1 Shopping

class buy:
  goods = [
      {"name": "Computer", "price": 1999},
      {"name": "Mouse", "price": 10},
      {"name": "Yacht", "price": 20},
      {"name": "Beauty", "price": 998},
    ]
  def __init __ (self, money, consumption, shopping_cart,):
    self.money = money
    self.consumption = consumption
    self.shopping_cart = shopping_cart
  def gouwu (self): #Shopping module
    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"]
      self.shopping_cart [self.goods [num] ["name"]] ['n'] + = 1 #number of products +1
    else:
      self.shopping_cart [self.goods [num] ["name"]] = {"price": self.goods [num] ["price"], 'n': 1,} # Create a shopping cart dictionary {keys {" price ": price, quantity: 1}}
    self.money- = self.shopping_cart [self.goods [num] ["name"]] ["price"] * self.shopping_cart [self.goods [num] ["name"]] ['n'] #Unit price * Quantity
    self.consumption + = self.shopping_cart [self.goods [num] ["name"]] ["price"] * self.shopping_cart [self.goods [num] ["name"]] ['n']
  def yichu (self): #Remove shopping cart module
    c = int (input ('Please enter 0/1 to choose whether to remove the shopping cart item, please enter 1:')
    if c == 1:
      e = int (input ('Please enter the serial number of the product to be removed:'))
      d = self.goods [e-1]
      if d in self.shopping_cart.keys (): #Determine if the item to be removed is in the shopping cart
        self.shopping_cart.remove (d) #Remove product
        self.money = self.money + self.goods [self.goods.index (d)] ["price"] #Balance increase
        self.consumption = self.consumption-self.goods [self.goods.index (d)] ["price"] #Total consumption decreases
      else:
        print ('Product does not exist')
  def chongzhi (self): #Recharge module
    pay = int (input ('Please enter the recharge amount'))
    self.money = self.money + pay
    print ('Your current balance is:% d'% self.money) #Show the current balance
  def main (self):
    print ('Product list:')
    for m, n in enumerate (self.goods, 1):
      print (m)
      for v in n.values ():
        print (v)
      print ('==============')
    # Clearing the total consumption
    self.consumption = 0
    buy = True #define default shopping all the time
    while buy:
      price = 0 #define initial price
      b = 1 #Define not to exit shopping or recharge status by default
      if self.money> = price:
    #Consumption module; you can start shopping when money is greater than the price of the goods
        while self.money> = price:
    #Counting module, you can always shop if you have money
          self.gouwu ()
    #Remove shopping cart product module
          self.yichu ()
          if self.money> = 0:
            print ('Your current balance is:% d'% self.money) #Show the current balance
            b = int (input ('Please enter 0/1 to choose whether to continue shopping, please enter 1:'))
            if b == 0: #
              break #Exit the pricing module
        if b == 0: #if not shopping
          break #Exit the entire shopping process without shopping
    # Top-up module
      else:
        while self.money <price: #Insufficient money, you can recharge multiple times until you can afford the goods
          a = int (input ('Your balance is insufficient, please enter 0/1 to choose whether to recharge, please enter 1:'))
          if a == 1:
            self.chongzhi ()
          else:
            break #Exit the recharge module
          if a == 0:
            break #Exit the program without recharging
    #Print shopping cart product name, product price, total consumption, balance
    print ('Your consumption list is:')
    for m, n in self.shopping_cart.items ():
      print (m, n ['price'], n ['n'])
          #Print consumption list
      print ('==============')
    print ('Your current balance is:% d, your total consumption is:% d'% (self.money, self.consumption)) #Print the total consumption
    return self.consumption
3.2.2 Credit Card ATM

class Atm:
  credit = 15000 #Credit card limit
  def __init __ (self, balance, debt, remaining_debt, interest, saving, id):
    self.id = id #credit card id
    self.balance = balance #Credit card available amount
    self.debt = debt #Total arrears
    self.remaining_debt = remaining_debt #Remaining balance
    self.interest = interest #Handling fees
    self.saving = saving #Deposit
    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): #Print account information
    return 'Account ID% s Credit Card Limit% s; Credit Card Available Amount% s; Remaining Debt% 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): #payment
    self.handel_money ('repay', amount)
  def withdraw (self, amount): #Cash
    self.handel_money ('withdraw', amount)
  def transfer (self, amount): #transfer
    self.handel_money ('transfer', amount)
  def consume (self, amount): #consumption
    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): #Transaction type,
    amount = int (amount)
    interest = amount * settings.TRANSACTION [transaction] ['interest'] #Commission fee calculation
    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: #Record flow information
      f.write (a)
    s = [self.balance, self.debt, self.remaining_debt, self.interest, self.saving,] #Update basic information
    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 socketserver
sys.path.append (os.path.dirname (os.path.dirname (__ file__)))
from config import settings
from lib import modules
from lib.modules import *
class Myserver (socketserver.BaseRequestHandler):
  def md5 (self, pwd):
    '' '
    Encrypt password
    : param pwd: password
    : 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):
    '' '
    Login
    : param usrname: username
    : param pwd: password
    : return: Whether the login was successful
    '' '
    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): #Compare with encrypted password
        return True
       else:
        return False
    else:
      return False
  def regist (self, usrname, pwd, x):
    '' '
    registered
    : param usrname: username
    : param pwd: password
    : return: whether the registration is 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 registration and login, and display user's detailed directory information, support cd and ls commands
    : 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: #User registration
        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 #The default value has been changed and the bank administrator has operated
        if ret [0] == 1: #if the administrator agrees
          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): #Interactive
    conn = self.request
    while True:
      c = conn.recv (1024) #Receive user interaction options
      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'))
      #Print account information
      obj = modules.Atm (s [0], s [1], s [2], s [3], s [4], usrname) #Atm object
      a = obj.account_info () #Receive account information
      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 ('Received User Category', 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) # Login or registration verification
        if x == '2': # After normal user authentication succeeds
          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 program serves as the entrance for users or bank administrators, where c = 1 represents bank administrators, c = 2 represents ordinary users
'' '
import pickle
import sys
import 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
  : param usrname: username
  : param pwd: password
  : return: Whether the login was successful
  '' '
  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
  : param usrname: username
  : param pwd: password
  : return: whether the registration is successful
  '' '
  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 registration to display the user's detailed directory information, support cd and ls commands
  : return:
  '' '
  a = input ('Please select 1. Login 2. Register')
  obj.sendall (bytes (a, encoding = 'utf-8'))
  obj.recv (1024)
  if a == '1':
    ret = login (usrname, pwd)
    if ret:
      print ('Successfully logged in')
      return 1
    else:
      print ('Wrong username or password')
      return 0
  elif a == '2':
    ret = regist (usrname, pwd, x)
    if ret:
      print ('Registration successful')
      return 1
    else:
      print ('The username already exists or the bank administrator has rejected')
      return 0
def main (x):
  usrname = input ('Please enter a username')
  pwd = input ('Please enter password')
  if user_identity_authentication (usrname, pwd, x): #If authentication is successful
    if x == '1': #Process user registration information
      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 ('User requests registration, input 1 agrees, 2 rejects')
            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 ('Wrong input')
          break
    else: #After regular user login
      interactive () #interactive
def interactive ():
  while True:
    a = input ('Please select 1. Repayment 2. Withdraw cash 3. Transfer 4. Consumption 5. Save money q Exit')
    obj.sendall (bytes (a, encoding = 'utf-8'))
    r = obj.recv (1024) #Receive account information
    ret = str (r, encoding = 'utf-8')
    print (ret)
    if a! = '4'and a! =' q ':
      b = input ('Please enter the amount')
      obj.sendall (bytes (b, encoding = 'utf-8'))
    elif a == 'q':
      break
obj = socket.socket () #Create a client socket object
obj.connect (('127.0.0.1', 9999))
while True:
  x = input ('Please select 1. Bank administrator 2. User q, log out')
  obj.sendall (bytes (x, encoding = 'utf-8'))
  obj.recv (1024) #Confirm receipt of user category
  if x == '1' or x == '2':
    main (x)
    break
  elif x == 'q':
    break
  else:
    print ('Wrong input, 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)
  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, calculates interest for each month's arrears. And write it into the bill for the month
    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 currently equal to 10 (before 9)
    # If the current balance is negative, the value will be added to the bill list to start interest calculation. At the same time, the available quota will be restored this month.
    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)
      # Restore available credit
      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 the entire content of the Python credit card system (supporting shopping, transfer, and deposit and withdrawal) introduced by Xiaobian to everyone. I hope it will be helpful to everyone. If you have any questions, please leave me a message. Xiaobian will reply in time Ours. Thank you very much for your support to the helper home website!

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.