模拟实现ATM与购物商城

2018-06-18 02:26:17来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

一、功能介绍(第6条未实现)
模拟实现一个ATM + 购物商城程序
1额度15000或自定义
2实现购物商城,买东西加入购物车,调用信用卡接口结账
3可以提现,手续费5%
4支持多账户登录
5支持账户间转账
6记录每月日常消费流水
7提供还款接口
8ATM记录操作日志
9提供管理接口,包括添加账户、用户额度,冻结账户等。。。
10用户认证用装饰器

二、实现流程图

三、程序目录结构

ATM_WHW
├── whw_atm
├── README.txt
├── atm #入口程序目录
│ ├── __init__.py
│ └── main.py #入口程序(启动程序)
├── conf #配置文件目录
│ ├── __init__.py
│ └── setting.py #里面包含日志的相关设置
├── logics #程序核心逻辑目录
│ ├── __init__.py
│ ├── admin_opera.py #管理员模块(用户名与密码均是:admin)
│ ├── authentication.py #认证模块,实现三种不同的登录模式
│ ├── creditcard_opera.py #信用卡操作模块
│ ├── shoppingmall.py #购物商城模块
│ ├── logger_opera.py #日志实现逻辑模块
├── db #程序所用到的静态数据(今后会是数据库的动态数据操作)
│ ├── creditcard_dict #信用卡信息
│ ├── productlist #商城产品信息
│ └── shopping_car #购物车信息
│ └── users_dict #用户信息
└── logs
├── __init__.py
└── access.log #记录操作日志
└── transactions.log #记录信用卡相关日志

四、具体模块代码

1.main.py

import os
import sys
from logics  import authentication,shoppingmall,creditcard_opera,admin_opera
#程序主目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#为程序添加环境变量
sys.path.append(BASE_DIR)


while 1:
    message = ''' 
1: 购物中心
2: 信用卡中心
3: 账户及信用卡管理
q: 退出系统
    '''
    print('欢迎进入信用卡及购物管理系统'.center(30,'#'))
    print(message)
    choice = input('请输入您想操作的编号:')
    if not choice or choice not in ['1','2','3','q']:
        print('请输入正确的编号!!!')
        continue
    if choice == '1':
        res = authentication.user_auth()
        if res != None:
            if res[0] == "True":
                current_user = res[1]#当前用户名
                shoppingmall.clear_shopping_car()
                while 1:
                    print('欢迎进入购物中心'.center(30,'#'),
                          '\n1:购物商场\n'
                          '2:查看购物车\n'
                          '3:购物结算\n'
                          '4:个人中心\n'
                          'b:返回\n'
                          )
                    choice = input('请输入要进行操作的对应编号:')
                    if choice == '1':
                        shoppingmall.shopping_mall()
                    elif choice == '2':
                        shoppingmall.shopping_car()
                    elif choice == '3':
                        shoppingmall.shopping_pay(current_user)
                    elif choice == '4':
                        while 1:
                            print('欢迎进入个人中心'.center(30,'^'),
                                  '\n1:绑定信用卡\n'
                                  '2:修改登陆密码\n'
                                  'b:返回上一级菜单'
                                  )
                            choice = input('请输入对应操作的编号:')
                            if choice == 'b':
                                break

                            elif choice == '1':
                                shoppingmall.creditcard_linked(current_user)


                            elif choice == '2':
                                shoppingmall.revise_password(current_user)
                            else:
                                print('请输入正确的编号!')
                    elif choice == 'b':
                        break

    elif choice == '2':
        res = authentication.creditcard_auth()
        ###############################################
        if res != None:
            if res[0] == 'True':
                current_creditcard = res[1]
                while 1:
                    print('欢迎进入信用卡中心'.center(30,'#'),
                          '\n1:信用卡信息\n' 
                          '2:提现\n' 
                          '3:转账\n' 
                          '4:还款\n' 
                          'b:返回')
                    choice_c = input('请输入您要进行的操作代码:')
                    if choice_c not in ['1','2','3','4','b'] or not choice_c:
                        print('请输入正确的编号!')
                        continue
                    elif choice_c == 'b':
                        break
                    elif choice_c == '1':
                        creditcard_opera.creditcard_msg(current_creditcard)
                    elif choice_c == '2':
                        creditcard_opera.creditcard_cash(current_creditcard)
                    elif choice_c == '3':
                        creditcard_opera.creditcard_transfer(current_creditcard)
                    elif choice_c == '4':
                        creditcard_opera.creditcard_payback(current_creditcard)


    elif choice == '3':
        res = authentication.admin_auth()
        if res != None:
            while 1:
                print('管理员中心'.center(30,'#'),
                      "\n1:创建账号\n"
                      "2:锁定账号\n"
                      "3:解锁账号\n"
                      "4:新建信用卡\n"
                      "5:冻结信用卡\n"
                      "6:解冻信用卡\n"
                      "b:返回"
                      )
                choice = input('请输入要进行的操作编号:')
                if not choice or choice not in ['1','2','3','4','5','6','b']:
                    print('请输入正确的编号!')
                    continue
                elif choice == 'b':
                    break
                elif choice == '1':
                    admin_opera.create_user()
                elif choice == '2':
                    admin_opera.user_locked()
                elif choice == '3':
                    admin_opera.user_unlock()
                elif choice == '4':
                    admin_opera.create_creditcard()
                elif choice == '5':
                    admin_opera.lock_creditcard()
                elif choice == '6':
                    admin_opera.unlock_creditcard()

    elif choice == 'q':
        print('退出程序!')
        exit()
View Code

2.setting.py

import os,logging
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

LOG_LEVEL = logging.INFO

LOG_TYPES = {
    'transaction':'transactions.log',
    'access':'access.log'
}
LOG_PATH = os.path.join(BASE_DIR,'logs')
LOG_FORMAT = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
View Code

3.db文件夹中的内容(存放的都是静态数据)

(1)creditcard_dict.json

{"666666": {"personinfo": "lisi", "password": "123", "limit": 2569, "locked": 0, "limitcash": 7500, "creditcard": "666666"}, "123456": {"personinfo": "whw", "password": "123", "limit": 9807.45, "locked": 0, "limitcash": 7500, "creditcard": "123456"}, "888888": {"personinfo": "zhangsan", "password": "123", "limit": 11313, "locked": 0, "limitcash": 7500, "creditcard": "888888"}, "654321": {"personinfo": "zhaosi", "password": "123", "limit": 14478, "locked": 0, "limitcash": 7500, "creditcard": "654321"}, "777777": {"personinfo": "wangwu", "password": "123", "limit": 14288, "locked": 0, "limitcash": 7500, "creditcard": "777777"}, "000000": {"personinfo": "wanghw", "password": "123", "limit": 11001, "locked": 0, "limitcash": 7500, "creditcard": "000000"}, "111111": {"personinfo": "fff", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "111111"}, "785458": {"personinfo": "ttt", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "785458"}, "999999": {"personinfo": "uuu", "password": "123", "limit": 14334, "locked": 0, "limitcash": 7500, "creditcard": "999999"}, "222222": {"personinfo": "ooo", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "222222"}, "909090": {"personinfo": "blank", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "909090"}}
View Code

(2)publiclist.json

Computer       2299
1080Ti         3999
keyboard       999
Cookbook       199
MATE10         3999
Beauty         1099
Dragon         666
View Code

(3)shoppingcar仅是一个临时存放数据的地方,当用户退出或者结账后里面的数据自动清空

(4)user_dict.json

{"zhangsan": {"creditcard": "888888", "locked": 0, "username": "zhangsan", "password": "123"}, "lisi": {"creditcard": "666666", "password": "123", "username": "lisi", "locked": 0}, "wangwu": {"creditcard": "777777", "locked": 0, "username": "wangwu", "password": "333"}, "zhaosi": {"creditcard": "654321", "password": "123", "username": "zhaosi", "locked": 0}, "whw": {"creditcard": "123456", "password": "123", "username": "whw", "locked": 0}, "www": {"username": "www", "password": "123", "creditcard": "0", "locked": 0}, "eee": {"username": "eee", "password": "123", "creditcard": "0", "locked": 1}, "wanghw": {"username": "wanghw", "password": "123", "creditcard": "000000", "locked": 0}, "fff": {"username": "fff", "password": "123", "creditcard": "111111", "locked": 0}, "ttt": {"username": "ttt", "password": "123", "creditcard": "785458", "locked": 0}, "rrr": {"username": "rrr", "password": "123", "creditcard": "0", "locked": 0}, "uuu": {"username": "uuu", "password": "123", "creditcard": "999999", "locked": 0}, "ooo": {"username": "ooo", "password": "321", "creditcard": "222222", "locked": 0}, "rty": {"username": "rty", "password": "123", "creditcard": "0", "locked": 0}}
View Code

4.logics文件夹中的内容(都是本程序的后台逻辑)

(1)admin_opera.py

import os,json
from .logger_opera import logger

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#信用卡与用户文件的相对路径
_user_dict = BASE_DIR + r'\db\user_dict.json'
_creditcard_dict = BASE_DIR + r'\db\creditcard_dict.json'

#负责记录各种操作
access_logger = logger('access')

#创建账户
def create_user(creditcard='0',locked=0):
    while 1:
        print('创建用户'.center(30,'*'))
        f_user_dict = open(_user_dict,'r+')
        user_dict = json.loads(f_user_dict.read())
        print('现有账户名信息如下:')
        for i,v in enumerate(user_dict,1):
            print('%s:%s' % (i,v))
        username = input('请输入要添加的账户名:')
        password = input('请输入想要添加的密码:')
        if username not in user_dict.keys():
            if len(username.strip()) > 0:
                if len(password.strip()) > 0:
                    #添加用户
                    user_dict[username] = {"username": username, "password": password, "creditcard": creditcard, "locked": locked}
                    new_user_dict = json.dumps(user_dict)
                    f_user_dict.seek(0)
                    f_user_dict.truncate(0)
                    f_user_dict.write(new_user_dict)
                    access_logger.info('create a new user: %s ' % username)
                    print("创建用户 %s 成功" % (username))
                    print('添加后的账户名信息如下:')
                    for i, v in enumerate(user_dict, 1):
                        print('%s:%s' % (i, v))
                    break
                else:
                    print("输入的密码为空")
            else:
                print("输入的用户名为空")
        else:
            print("用户名 %s 已经存在" % (username))


#锁定账号
def user_locked():
    while 1:
        print('锁定账户'.center(30,'+'))
        f_user_dict = open(_user_dict,'r+')
        user_dict = json.loads(f_user_dict.read())
        print('账户锁定状态如下:')
        for i in user_dict:
            if user_dict[i]['locked'] == 0:
                print('用户 %s 未被锁定!' % i)
            else:
                print('用户 %s 已被锁定' % i)
        lock_input = input('请输入要锁定的用户:')
        if not lock_input:continue
        if lock_input  in user_dict.keys():
            sure = input('是否确定进行锁定操作?确定【y】,返回上一级【b】')
            if sure == 'y':
                if user_dict[lock_input]['locked'] == 0:
                    user_dict[lock_input]['locked'] = 1
                    new_user_dict = json.dumps(user_dict)
                    f_user_dict.seek(0)
                    f_user_dict.truncate(0)
                    f_user_dict.write(new_user_dict)
                    print('账户 %s 锁定成功!' % lock_input)
                    access_logger.info('user %s just be locked!' % lock_input)
                    print('修改后的账户锁定状态如下:')
                    for i in user_dict:
                        if user_dict[i]['locked'] == 0:
                            print('用户 %s 未被锁定!' % i)
                        else:
                            print('用户 %s 已被锁定' % i)
                    break
                else:
                    print('操作失败!该账户之前已被锁定!')
            elif sure == 'b':
                break
            else:
                print('请输入正确的操作编码!')
                break
        else:
            print('账户名不存在,请重新输入!')
            continue


#解锁账号
def user_unlock():
    while 1:
        print('解锁用户'.center(30,'-'))
        f_user_dict = open(_user_dict, 'r+')
        user_dict = json.loads(f_user_dict.read())
        print('账户锁定状态如下:')
        for i in user_dict:
            if user_dict[i]['locked'] == 0:
                print('用户 %s 未被锁定!' % i)
            else:
                print('用户 %s 已被锁定' % i)
        unlock_input = input('请输入需要解锁的用户:')
        if not unlock_input:continue
        if unlock_input  in user_dict.keys():
            sure = input('是否确定进行解锁操作?确定【y】,返回上一级【b】')
            if sure == 'y':
                if user_dict[unlock_input]['locked'] != 0:
                    user_dict[unlock_input]['locked'] = 0
                    new_user_dict = json.dumps(user_dict)
                    f_user_dict.seek(0)
                    f_user_dict.truncate(0)
                    f_user_dict.write(new_user_dict)
                    print('账户 %s 解锁成功!' % unlock_input)
                    access_logger.info('user %s just be unlocked!' % unlock_input)
                    print('修改后的账户锁定状态如下:')
                    for i in user_dict:
                        if user_dict[i]['locked'] == 0:
                            print('用户 %s 未被锁定!' % i)
                        else:
                            print('用户 %s 已被锁定' % i)
                    break
                else:
                    print('操作失败!该账户之前未被锁定!')
            elif sure == 'b':
                break
            else:
                print('请输入正确的操作编码!')
                break
        else:
            print('账户名不存在,请重新输入!')
            continue


#新建信用卡
def create_creditcard(personinfo='blank',limit=15000,locked=0,limitcash=7500):
    while 1:
        print('新建信用卡'.center(30,'+'))
        f_creditcard_dict = open(_creditcard_dict,'r+')
        creditcard_dict = json.loads(f_creditcard_dict.read())
        print('现有信用卡信息如下:')
        for index in creditcard_dict:
            print('信用卡 %s >> 持卡人 %s'% (index,creditcard_dict[index]['personinfo']))
        new_card = input('请输入要发行的信用卡卡号:')
        if not new_card:continue
        if new_card.isdigit():
            if len(new_card.strip()) == 6:
                if new_card not in creditcard_dict.keys():
                    password = input('请输入新增信用卡的密码:')
                    if len(password.strip()) > 0:
                        #新增信用卡
                        creditcard_dict[new_card] = {"personinfo": personinfo, "password": password, "limit": limit, "locked": 0,
                                                     "limitcash": limit//2, "creditcard": new_card}
                        new_creditcard_dict = json.dumps(creditcard_dict)
                        f_creditcard_dict.seek(0)
                        f_creditcard_dict.truncate(0)
                        f_creditcard_dict.write(new_creditcard_dict)
                        access_logger.info('create a new creditcard: %s ' % new_card)
                        print('信用卡新增成功!新的信用卡信息如下:')
                        for index in creditcard_dict:
                            print('信用卡 %s >> 持卡人 %s'% (index,creditcard_dict[index]['personinfo']))
                        break
                    else:
                        print('信用卡密码不能为空!')
                else:
                    print('该卡号已存在!')
            else:
                print('信用卡卡号必须是6位数字!')
        else:
            print('请输入数字!')


#冻结信用卡
def lock_creditcard():
    while 1:
        print('冻结信用卡'.center(30,'-'))
        f_creditcard_dict = open(_creditcard_dict, 'r+')
        creditcard_dict = json.loads(f_creditcard_dict.read())
        print('现有信用卡信息如下:')
        for index in creditcard_dict:
            if creditcard_dict[index]['locked'] == 0:
                print('信用卡 %s >>> %s' % (index,'未冻结'))
            else:
                print('信用卡 %s >>> %s' % (index, '已冻结'))
        lock_card = input('请输入要冻结的信用卡卡号:')
        if lock_card.isdigit() and len(lock_card) ==6:
            if lock_card in creditcard_dict.keys():
                if_lock = input('是否冻结该信用卡:%s。确认【y】,返回【b】' % lock_card)
                if if_lock == 'b':
                    break
                elif if_lock == 'y':
                    creditcard_dict[lock_card]['locked'] = 1
                    new_creditcard_dict = json.dumps(creditcard_dict)
                    f_creditcard_dict.seek(0)
                    f_creditcard_dict.truncate(0)
                    f_creditcard_dict.write(new_creditcard_dict)
                    access_logger.info('creditcard %s just be locked!' % lock_card)
                    print('信用卡 %s 已成功冻结!' % lock_card)
                    print('更改后的信用卡信息如下:')
                    for index in creditcard_dict:
                        if creditcard_dict[index]['locked'] == 0:
                            print('信用卡 %s >>> %s' % (index, '未冻结'))
                        else:
                            print('信用卡 %s >>> %s' % (index, '已冻结'))
                    break
                else:
                    print('请输入正确的操作信息!')
            else:
                print('该信用卡卡号不存在!')
        else:
            print('请输入正确的卡号格式!')
            continue


#解冻信用卡
def unlock_creditcard():
    while 1:
        print('解冻信用卡'.center(30,'-'))
        f_creditcard_dict = open(_creditcard_dict, 'r+')
        creditcard_dict = json.loads(f_creditcard_dict.read())
        print('现有信用卡信息如下:')
        for index in creditcard_dict:
            if creditcard_dict[index]['locked'] == 0:
                print('信用卡 %s >>> %s' % (index,'未冻结'))
            else:
                print('信用卡 %s >>> %s' % (index, '已冻结'))
        ulock_card = input('请输入要解冻的信用卡卡号:')
        if ulock_card.isdigit() and len(ulock_card) ==6:
            if ulock_card in creditcard_dict.keys():
                if_lock = input('是否解冻该信用卡:%s。确认【y】,返回【b】' % ulock_card)
                if if_lock == 'b':
                    break
                elif if_lock == 'y':
                    creditcard_dict[ulock_card]['locked'] = 0
                    new_creditcard_dict = json.dumps(creditcard_dict)
                    f_creditcard_dict.seek(0)
                    f_creditcard_dict.truncate(0)
                    f_creditcard_dict.write(new_creditcard_dict)
                    access_logger.info('creditcard %s just be unlocked!' % ulock_card)
                    print('信用卡 %s 已成功解冻!' % ulock_card)
                    print('更改后的信用卡信息如下:')
                    for index in creditcard_dict:
                        if creditcard_dict[index]['locked'] == 0:
                            print('信用卡 %s >>> %s' % (index, '未冻结'))
                        else:
                            print('信用卡 %s >>> %s' % (index, '已冻结'))
                    break
                else:
                    print('请输入正确的操作信息!')
            else:
                print('该信用卡卡号不存在!')
        else:
            print('请输入正确的卡号格式!')
            continue
View Code

(2)authentication.py

import os
import json

#程序主目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#数据库文件:用户文件与信用卡文件——相对路径
users_dict = BASE_DIR + r'\db\user_dict.json'
creditcard_dict = BASE_DIR + r'\db\creditcard_dict.json'

#认证——装饰器
def login(auth_type):
    def auth(func):
        #用户名认证
        if auth_type == 'user_auth':
            def inner():
                res = func()
                n = 0
                while n < 3:#用户有三次输入的机会
                    username = input('请输入用户名:')
                    password = input('请输入密码:')
                    if not username or not password:
                        print('用户名或密码不能为空,请重新输入!')
                        n += 1
                        continue
                    f = open(users_dict,'r+')
                    users_dict_j = json.loads(f.read())#loads
                    if username in users_dict_j.keys():
                        if password in users_dict_j[username]["password"]:
                            if users_dict_j[username]['locked'] == 0:
                                print('用户 %s 认证成功!' % username)
                                return res,username
                            else:
                                print('用户 %s 已被锁定!' % username)
                                break
                        else:
                            print('密码不匹配!')
                            n += 1
                            continue
                    else:
                        print('用户名不匹配!')
                        n += 1
                        continue
            return inner
        #信用卡认证
        if auth_type == 'creditcard_auth':
            def inner():
                res = func()
                n = 0
                while n < 3:
                    creditcard = input('请输入信用卡卡号(6位数字):')
                    password = input('请输入信用卡密码:')
                    if not creditcard or not password:
                        print('卡号或者密码不能为空,请重新输入!')
                        n += 1
                        continue
                    f = open(creditcard_dict,'r+')
                    creditcard_dict_j = json.loads(f.read())
                    if creditcard in creditcard_dict_j.keys():
                        if password in creditcard_dict_j[creditcard]['password']:
                            if creditcard_dict_j[creditcard]['locked'] == 0:
                                print('信用卡 %s 认证成功!' % creditcard)
                                return res,creditcard
                            else:
                                print('该信用卡已被冻结!')
                                break
                        else:
                            print('密码错误!')
                            n += 1
                            continue
                    else:
                        print('卡号错误!')
                        n += 1
                        continue
            return inner
        #管理员认证
        if auth_type == 'admin_auth':
            def inner():
                res = func()
                #规定admin账户只能是这一个唯一的账户
                admin_dict = {'admin':'admin'}
                n = 0
                while n < 3:
                    admin_name = input('请输入管理员账户:')
                    admin_password = input('请输入管理员密码:')
                    if not admin_name or not admin_password:
                        print('账户名或密码不能为空!')
                        n += 1
                        continue
                    if admin_name in admin_dict:
                        if admin_password in admin_dict:
                            print('管理员账户 %s 认证成功!' % admin_name)
                            return res,admin_name
                        else:
                            print('密码不匹配!!')
                            n += 1
                            continue
                    else:
                        print('管理员账户名不匹配:')
                        n += 1
                        continue
            return inner
    return auth

#用户以三种方式登陆:用户名、信用卡、后台管理员
@login('user_auth')
def user_auth():
    print('用户登陆认证:'.center(30,'+'))
    return 'True'

@login('creditcard_auth')
def creditcard_auth():
    print('信用卡登陆认证:'.center(30,'+'))
    return 'True'

@login('admin_auth')
def admin_auth():
    print('后台管理员登陆认证:'.center(30,'+'))
    return 'True'
View Code

(3)creditcard_opera.py

import os,json
from.logger_opera import logger

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#信息文件的相对路径:
_creditcard_dict = BASE_DIR + r'\db\creditcard_dict.json'



#负责记录各种交易
transaction_logger = logger('transaction')


#本信用卡信息
def creditcard_msg(current_creditcard):
    while 1:
        print('本信用卡信息:'.center(30,'*'))
        f_creditcard_dict = open(_creditcard_dict,'r')
        creditcard_dict = json.loads(f_creditcard_dict.read())
        #先判断提现额度
        if creditcard_dict[current_creditcard]['limitcash'] <= creditcard_dict[current_creditcard]['limit']:
            limitcash = creditcard_dict[current_creditcard]['limitcash']
        else:
            limitcash = creditcard_dict[current_creditcard]['limit']
        print("卡号:\t【%s】\n余额:\t【¥%s】\n提现额度:\t【¥%s】\n持卡人:\t【%s】\n"%(current_creditcard,
                creditcard_dict[current_creditcard]["limit"],limitcash,creditcard_dict[current_creditcard]["personinfo"]))
        choice = input('是否返回?【b】返回')
        if choice == 'b':
            break
        else:
            print('请输入【b】返回')
            continue


#提现
def creditcard_cash(current_creditcard):
    while 1:
        print('信用卡提现操作(手续费为%5)'.center(30,'*'))
        f_creditcard_dict = open(_creditcard_dict,'r+')
        creditcard_dict = json.loads(f_creditcard_dict.read())
        limit = creditcard_dict[current_creditcard]['limit']
        limitcash = creditcard_dict[current_creditcard]['limitcash']
        if limit >= limitcash:
            print('可提现的金额为:%s' % limitcash)
            cash_input = input('请输入要提取的金额:')
            if not cash_input or not cash_input.isdigit():#输入为空或非数字
                print('请输入数字!')
                continue
            cash = int(cash_input)
            if cash != 0:
                if cash <= limitcash:
                    limit = limit - (cash*1.05)
                    creditcard_dict[current_creditcard]['limit'] = limit
                    creditcard_dict_new = json.dumps(creditcard_dict)
                    f_creditcard_dict.seek(0)
                    f_creditcard_dict.truncate(0)
                    f_creditcard_dict.write(creditcard_dict_new)
                    #日志
                    transaction_logger.info('信用卡 %s 提现 %s元' % (current_creditcard,cash_input))
                    print('提现成功!当前余额为: %s ' % creditcard_dict[current_creditcard]['limit'])
                    break
                else:
                    print('提现金额超出信用卡限额!')
            else:
                print('提现金额不能为空!')
        if limit < limitcash:
            print("可提现金额:【%s】(扣除0.05手续费)\n" % (int(limit*0.95)))
            cash_input = input('请输入要提取的金额:')
            if not cash_input or not cash_input.isdigit():  # 输入为空或非数字
                print('请输入数字!')
                continue
            cash = int(cash_input)
            if cash != 0:
                if cash < limit*0.95:
                    limit = limit - (cash * 1.05)
                    creditcard_dict[current_creditcard]['limit'] = limit
                    creditcard_dict_new = json.dumps(creditcard_dict)
                    f_creditcard_dict.seek(0)
                    f_creditcard_dict.truncate(0)
                    f_creditcard_dict.write(creditcard_dict_new)
                    # 日志
                    transaction_logger.info('信用卡 %s 提现 %s元' % (current_creditcard, cash_input))
                    print('提现成功!当前余额为: %s ' % creditcard_dict[current_creditcard]['limit'])
                    break
                else:
                    print('提现金额超出信用卡限额!')
            else:
                print('提现金额不能为空!')


#转账
def creditcard_transfer(current_creditcard):
    while 1:
        print('信用卡转账'.center(30,'*'))
        f_creditcard_dict = open(_creditcard_dict,'r+')
        creditcard_dict = json.loads(f_creditcard_dict.read())
        trans_input = input('(您的余额为%s)请输入要转入的卡号:' % creditcard_dict[current_creditcard]['limit'])
        if  trans_input or  trans_input.isdigit() or len(trans_input) == 6:
            if trans_input in creditcard_dict.keys():
                transfer_cash = input('请输入您要转入的金额:')
                if transfer_cash or transfer_cash.isdigit():
                    transfer_cash = int(transfer_cash)
                    if transfer_cash < creditcard_dict[current_creditcard]['limit']:
                        creditcard_dict[current_creditcard]['limit'] -= transfer_cash
                        creditcard_dict[trans_input]['limit'] += transfer_cash
                        creditcard_dict_new = json.dumps(creditcard_dict)
                        f_creditcard_dict.seek(0)
                        f_creditcard_dict.truncate(0)
                        f_creditcard_dict.write(creditcard_dict_new)
                        # 日志
                        transaction_logger.info('信用卡 %s 给信用卡 %s 转账 %s元' % (current_creditcard,trans_input,transfer_cash))
                        print('转账成功!您的当前余额为: %s' % (creditcard_dict[current_creditcard]['limit']))
                        break
                    else:
                        print('对不起,您的金额不足,转账失败!')
                else:
                    print('金额输入有误!')
            else:
                print('该信用卡卡号不存在!')
        else:
            print('银行卡号输入有误!')


#还款
def creditcard_payback(current_creditcard):
    while 1:
        print('信用卡还款'.center(30,'*'))
        f_creditcard_dict = open(_creditcard_dict,'r+')
        creditcard_dict = json.loads(f_creditcard_dict.read())
        payback = input('请输入还款金额:')
        if payback and payback.isdigit():
            payback = int(payback)
            creditcard_dict[current_creditcard]['limit'] += payback
            new_creditcard_dict = json.dumps(creditcard_dict)
            f_creditcard_dict.seek(0)
            f_creditcard_dict.truncate(0)
            f_creditcard_dict.write(new_creditcard_dict)
            # 日志
            transaction_logger.info('信用卡 %s 还款 %s元' % (current_creditcard, payback))
            print('信用卡 %s 还款成功!当前余额为:%s' % (current_creditcard,creditcard_dict[current_creditcard]['limit']))
            break
        else:
            print('请输入正确的金额!')
View Code

(4)logger_opera.py

import logging,os
from conf import settings

def logger(log_type):
    #新建日志
    logger = logging.getLogger(log_type)
    #拿到settings文件里的LOG_LEVEL:当前设置为logging.INFO
    logger.setLevel(settings.LOG_LEVEL)
    #根据log_type 决定往哪个log文件里写
    log_file = os.path.join(settings.LOG_PATH,settings.LOG_TYPES[log_type])
    #决定往哪里写后进行操作
    fh = logging.FileHandler(log_file)
    fh.setLevel(settings.LOG_LEVEL)
    formatter = settings.LOG_FORMAT

    #formatter:
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    return logger
View Code

(5)shoppingmall.py

import json,os
from .logger_opera import logger

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#数据库文件的相对路径:
_user_dict = BASE_DIR + r'\db\user_dict.json'
_creditcard_dict = BASE_DIR + r'\db\creditcard_dict.json'
_productlist = BASE_DIR + r'\db\productlist.json'
_shoppingcar = BASE_DIR + r'\db\shoppingcar'


#负责记录各种交易
transaction_logger = logger('transaction')


#清空购物车
def clear_shopping_car():
    f = open(_shoppingcar,'w')
    l = json.dumps([])
    f.write(l)


#购物商城
def shopping_mall():
    shopping_list,pro_list = [],[]
    f_pro = open(_productlist,'r')
    for i in f_pro:
        #得到商品列表,pro_list里面是:[['computer', '2299'], ['1080Ti', '3999'], ...]
        pro_list.append(i.strip("\n").split())
    while 1:
        print(('商城目前正在出售的商品及价格信息:').center(30,'#'))
        print('编号\t商品\t\t\t价格')
        for i,v in enumerate(pro_list):
            print('%s\t%s:  %s' % (i,v[0],v[1]))#打印商品列表
        choice = input('请输入想要购买的商品编号或者输入\'b\'返回:')
        if choice.isdigit():
            choice = int(choice)
            if 0 <= choice < len(pro_list):
                pro_item = pro_list[choice]
                print('已将商品 %s 加入购物车,价格为%s '% (pro_item[0],pro_item[1]))
                shopping_list.append(pro_item)
            else:
                print('错误!没有对应的编号,请重新输入!')

        elif choice == 'b':
            f_shopping_car = open(_shoppingcar,'r+')
            list_s = json.loads(f_shopping_car.read())
            #注意这里是extend而不是append,append会使价格v[1]取成一个列表
            list_s.extend(shopping_list)
            f_shopping_car.seek(0)
            f_shopping_car.truncate(0)
            list_s = json.dumps(list_s)
            f_shopping_car.write(list_s)
            break
        else:
            print('错误~没有对应的编号,请重新输入!')


#查看购物车
def shopping_car():
    while 1:
        f_shopping_car = open(_shoppingcar,'r+')
        l_shopping_car = json.loads(f_shopping_car.read())
        n = 0
        print('购物车信息清单如下:'.center(30,'*'))
        for i,v in enumerate(l_shopping_car):
            print(i,v[0],v[1])
            n += int(v[1])#计算商品总价格
        print('购物车中商品的总额为:%d 元' % n)
        choice_in = input('请选择要进行的操作:返回【b】/清空【c】')
        if choice_in == 'b':
            break
        elif choice_in == 'c':
            clear_shopping_car()
        else:
            print('请重新输入正确的编号')


#购物结算前进行信用卡密码认证
def Auth_creditcard(creditcard):
    with open(_creditcard_dict, "r+") as f_creditcard_dict:
        creditcard_dict = json.loads(f_creditcard_dict.read())
        passwd = input("当前信用卡 %s 请输入支付密码::" % (creditcard))
        if passwd == creditcard_dict[creditcard]["password"]:
            return True
        else:
            print("密码输入错误,支付失败")


#购物结算
def shopping_pay(current_user):
    while 1:
        money = 0
        print('购物结算'.center(30,'$'))
        f_shopping_car = open(_shoppingcar,'r+')
        l_shopping_car = json.loads(f_shopping_car.read())
        for item in l_shopping_car:
            money += int(item[1]) #购物车里商品的总钱数
        pay_input = input('当前商品总额为 %d,是否进行支付?确定【y】/返回【b】' % money)
        if pay_input == 'b':
            break
        elif pay_input == 'y':
            f_user_dict = open(_user_dict,'r+')
            user_dict = json.loads(f_user_dict.read())
            creditcard = user_dict[current_user]['creditcard']#找到账户对应的信用卡
            if creditcard == '0':
                print('账户 %s 还未绑定信用卡,请进入个人中心绑定信用卡后再进行操作' % current_user)
            else:
                f_creditcard_dict = open(_creditcard_dict,'r+')
                creditcard_dict = json.loads(f_creditcard_dict.read())
                limit = creditcard_dict[creditcard]['limit']
                limit_new = limit - money
                if limit_new < 0:
                    print('当前信用卡额度为:%s元,不足以支付购物款:%s元',(limit,money))
                else:
                    res = Auth_creditcard(creditcard)
                    if res == True:
                        creditcard_dict[creditcard]['limit'] = limit_new
                        new_creditcard_dict = json.dumps(creditcard_dict)
                        f_creditcard_dict.seek(0)
                        f_creditcard_dict.truncate(0)
                        f_creditcard_dict.write(new_creditcard_dict)
                        print('支付成功,当前余额为 %s元' % limit_new)
                        #记录日志
                        transaction_logger.info('用户 %s 购买产品花费 %s' %(current_user,money))
                        clear_shopping_car()#最后清空当前购物车
                        break


#信用卡绑定
def creditcard_linked(current_user):
    while 1:
        print('信用卡绑定'.center(30,'*'))
        f_user_dict = open(_user_dict,'r+')
        user_dict = json.loads(f_user_dict.read())
        creditcard = user_dict[current_user]['creditcard']
        if creditcard == '0':
            print('当前账号 %s 未绑定信用卡' % current_user)
        else:
            print('当前账号 %s 已经绑定了信用卡:%s,不可以重复绑定!' % (current_user,creditcard))
            break
        link_input = input('是否要修改信用卡绑定? 确定【y】/返回【b】')
        if link_input.strip() == 'b':
            break
        if link_input.strip() == 'y':
            creditcard_new = input('请输入新的信用卡卡号(6位数字):')
            if creditcard_new.isdigit() and len(creditcard_new) == 6:
                f_creditcard_dict = open(_creditcard_dict,'r+')
                creditcard_dict = json.loads(f_creditcard_dict.read())
                if creditcard_new not in creditcard_dict.keys():
                    print('输入信用卡卡号不存在(或者未发行)!')
                #信用卡的持卡人信息为blank(代表这个卡没有人绑定)
                if creditcard_dict[creditcard_new]['personinfo'] == 'blank':
                    creditcard_dict[creditcard_new]['personinfo'] = current_user
                    user_dict[current_user]['creditcard'] = creditcard_new
                    #新的信用卡信息
                    dict_creditcard = json.dumps(creditcard_dict)
                    f_creditcard_dict.seek(0)
                    f_creditcard_dict.truncate(0)
                    f_creditcard_dict.write(dict_creditcard)
                    #新的人员信息
                    dict_users = json.dumps(user_dict)
                    f_user_dict.seek(0)
                    f_user_dict.truncate(0)
                    f_user_dict.write(dict_users)
                    #记录日志
                    transaction_logger.info('用户 %s 绑定信用卡 %s!' % (current_user,creditcard_new))
                    print('用户 %s 已成功绑定信用卡 %s!' % (current_user,creditcard_new))
                    break
                else:
                    print('信用卡 %s 已绑定用户,不可以再绑定!' % creditcard_new)
            else:
                print('请输入正确格式的信用卡卡号')
        else:
            print('请输入正确的操作编号!')


#修改登陆密码
def revise_password(current_user):
    while 1:
        print('修改用户登陆密码'.center(30,'*'))
        f_user_dict = open(_user_dict,'r+')
        user_dict = json.loads(f_user_dict.read())
        old_password = user_dict[current_user]['password']
        old_password_o = input('请输入旧密码:')
        if old_password_o != old_password:
            print('旧密码不正确!')
            break
        new_password = input('请输入新密码:')
        new_password_again = input('请确认新密码:')
        if new_password == new_password_again:
            user_dict[current_user]['password'] = new_password
            new_user_dict = json.dumps(user_dict)
            f_user_dict.seek(0)
            f_user_dict.truncate(0)
            f_user_dict.write(new_user_dict)
            #记录日志
            transaction_logger.info('用户 %s 修改了密码' % current_user)
            print('用户 %s 密码修改成功!' % current_user)
            break
        else:
            print('两次输入的密码不一致!')
            break
View Code

5.logs文件夹中的内容(存放的都是日志信息)

(1)access.log

2018-04-17 17:41:37,130 - access - INFO - create a new user: rty 
2018-04-17 17:41:49,616 - access - INFO - user rty just be locked!
2018-04-17 17:41:56,711 - access - INFO - user rty just be unlocked!
2018-04-17 17:42:08,399 - access - INFO - create a new creditcard: 909090 
2018-04-17 17:42:21,666 - access - INFO - creditcard 909090 just be locked!
2018-04-17 17:42:29,636 - access - INFO - creditcard 909090 just be unlocked!
2018-04-17 18:01:53,331 - access - INFO - creditcard 000000 just be unlocked!
View Code

(2)transactions.log

2018-04-17 17:34:09,615 - transaction - INFO - 用户 whw 购买产品花费 4998
2018-04-17 17:34:23,226 - transaction - INFO - 用户 whw 修改了密码
2018-04-17 17:40:41,468 - transaction - INFO - 信用卡 123456 提现 333元
2018-04-17 17:40:49,250 - transaction - INFO - 信用卡 123456 给信用卡 666666 转账 11元
2018-04-17 17:40:55,188 - transaction - INFO - 信用卡 123456 还款 222元
View Code

  最后,由于程序的运行情况十分繁琐这里就不再一一截图了。

  本文章仅提供一种实现的思路,当然由于本人还是新手级别,所以代码在重用性与健壮性上与成熟的代码还有很大的差距,希望大家看后给一些意见,十分感谢!

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python学习第四天——文件修改

下一篇:搭建python环境