python基础实战项目——ATM+购物车代码大全

需求分析

1.实现用户的登录注册功能,并且用户分为普通用户和管理员用户,登录时需要先输入验证码
2.用户注册时会自动添加 20000 元的余额,与 0 元的银行卡信用余额
3.用户拥有–充值,提现,转账,还款,查询银行流水的基本功能
4.用户可以进入购物界面,能够添加物品进入购物车中
5.用户可以查询当前购物车中的物品,可以结算购物车中的所有商品
6.可以修改购物车中的商品
7.可以查询所有的购物历史
8.对于管理员的用户,可以冻结账户,重置账户密码,删除账户,解冻用户,查看指定用户信息
9.对于管理员用户,以及操作账户金额的所有功能需要记录日志

项目功能

1.注册
2.登陆
3.查看余额
4.提现
5.还款
6.转账
7.查看流水
8.添加购物车功能
9.查看购物车功能
10.结算购物车功能
11.管理员功能

架构设计

三层架构

在这里插入图片描述
在这里插入图片描述

视图层

视图层是应用程序的用户界面和通信层,供最终用户与应用程序进行交互。 其主要目的是向用户显示信息并从用户收集信息。 此顶级层可以在(例如)Web 浏览器上运行、作为桌面应用程序运行或作为图形用户界面 (GUI) 运行。 Web 表示层通常使用 HTML、CSS 和 JavaScript 开发。 可根据平台以各种不同语言编写桌面应用程序。

接口层

接口层,也称为逻辑层或中间层,是应用程序的核心。 在该层中,将采用业务逻辑(一组特定的业务规则)处理从表示层收集到的信息, 有时也会处理数据层中的其他信息 。 接口层还可以添加、删除或修改数据层中的数据。
接口层通常使用 Python、Java、Perl、PHP 或 Ruby 开发,并使用 API 调用与数据层通信。

数据处理层

数据处理层层(有时称为数据库层、数据访问层或后端)可供存储和管理应用程序所处理的信息。 这可以是关系 数据库管理系统,例如 PostgreSQL、MySQL、MariaDB、Oracle、DB2、Informix 或 Microsoft SQL Server,也可以是 NoSQL 数据库服务器,如 Cassandra、CouchDB 或 MongoDB。

在三层应用程序中,所有通信均通过接口层进行。 视图层和数据层无法直接彼此通信

项目代码

start.py-启动文件

import sys
import os

dir_path = os.path.dirname(os.path.dirname(__file__))
sys.path.append(dir_path)

from ATM购物车.core import src

if __name__ == '__main__':
    src.run()

conf文件夹
settings.py–配置文件

import os

GOOD_LIST = [
    ['挂壁面', 3],
    ['印度飞饼', 22],
    ['极品木瓜', 666],
    ['土耳其土豆', 999],
    ['伊拉克拌面', 1000],
    ['董卓戏张飞公仔', 2000],
    ['仿真玩偶', 10000],
    ['香奈儿', 20000],
    ['GUCCI', 5000],
    ['雅思兰黛粉底液', 599],
    ['LV手链', 15000],
    ['兰博基尼', 10000000]
]

MONEY_RATE = 0.01

Real_path = os.path.dirname(__file__)
File_path = os.path.join(Real_path, 'db')
if not os.path.exists(File_path):
    os.mkdir(File_path)
Bank_path = os.path.join(Real_path, 'bank')
if not os.path.exists(Bank_path):
    os.mkdir(Bank_path)

# 定义日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]'  # 其中name为getlogger指定的名字
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

# 自定义文件路径
user_path1 = os.path.dirname(os.path.dirname(__file__))
db_path = os.path.join(user_path1, 'log')
if not os.path.exists(db_path):
    os.mkdir(db_path)
logfile_path = os.path.join(db_path, 'log.log')
# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},  # 过滤日志
    'handlers': {
        # 打印到终端的日志
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        # 打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path,  # 日志文件
            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
        # logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['default'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },  # 当键不存在的情况下 (key设为空字符串)默认都会使用该k:v配置
        # '购物车记录': {
        #     'handlers': ['default','console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
        #     'level': 'WARNING',
        #     'propagate': True,  # 向上(更高level的logger)传递
        # },  # 当键不存在的情况下 (key设为空字符串)默认都会使用该k:v配置
    },
}

lib文件夹
common.py–公共方法

import logging
import logging.config
import hashlib
import random
from ATM购物车.conf import settings
from ATM购物车.core import src
from ATM购物车.database import db_handler


def get_logger(msg):
    # 记录日志
    logging.config.dictConfig(settings.LOGGING_DIC)  # 自动加载字典中的配置
    logger1 = logging.getLogger(msg)
    # logger1.debug(f'{username}注册成功')  # 这里让用户自己写更好
    return logger1


def get_md5(pwd):  # 函数传参的形式
    md = hashlib.md5()
    md.update('加盐'.encode('utf-8'))
    md.update(pwd.encode('utf-8'))
    return md.hexdigest()


def random_verify():
    sum = ''
    for i in range(5):
        random_number = str(random.randint(0, 9))
        random_update = chr(random.randint(65, 90))
        random_lower = chr(random.randint(97, 122))
        res = random.choice([random_number, random_update, random_lower])
        sum = res + sum
    return sum


def outer(func_name):
    def inner(*args, **kwargs):
        if src.user_judge.get('username') and src.user_judge.get('is_tage') == False:
            res = func_name(*args, **kwargs)
            return res
        elif src.user_judge.get('is_tage') == True:
            print('该用户已经被冻结')

        else:
            print('你没有权限,请先登录')
            src.login()

    return inner


def out(func):
    def inn(*args, **kwargs):
        shop_operate_info = db_handler.select(src.user_judge.get('username'))
        if shop_operate_info.get('is_admin'):
            res = func(*args, **kwargs)
            return res
        else:
            print('你不是管理员')

    return inn

database文件夹–数据库
db_handler–数据处理

import os
import json
from ATM购物车.conf import settings


def register_db(user_dict, bank_dict):
    username = user_dict.get('username')
    user_path = os.path.join(settings.File_path, username)
    with open(user_path, 'w', encoding='utf8') as f:
        json.dump(user_dict, f)
    # 用户银行卡注册
    user_bank_path = os.path.join(settings.Bank_path, '%s.bank' % username)
    with open(user_bank_path, 'w', encoding='utf8') as f:
        json.dump(bank_dict, f)
    return f'用户{username}注册成功'


def select(public):
    user_path = os.path.join(settings.File_path, public)
    if os.path.exists(user_path):
        with open(user_path, 'r', encoding='utf8') as f:
            user_info = json.load(
                f)  # {"username": "lzq", "pwd": "f9eddd2f29dcb3136df2318b2b2c64d3", "balance": 20000, "shop_car": {}, "flow": [], "is_tage": false, "is_admin": false}
            return user_info


def select_bank(public):
    user_bank_path = os.path.join(settings.Bank_path, '%s.bank' % public)
    with open(user_bank_path, 'r', encoding='utf8') as f:
        user_bank_info = json.load(f)
        return user_bank_info


def shop_w_db(username, shop_info):
    user_path = os.path.join(settings.File_path, username)
    with open(user_path, 'w', encoding='utf8') as f:  # 购物车
        json.dump(shop_info, f, ensure_ascii=False)


def bank_w_db(username, bank_info):
    money_path = os.path.join(settings.Bank_path, '%s.bank' % username)
    with open(money_path, 'w', encoding='utf8') as f:  # 银行
        json.dump(bank_info, f, ensure_ascii=False)

core文件夹–视图层
src.py-用户视图(主视图)

from ATM购物车.lib import common
from ATM购物车.interface import user_interface
from ATM购物车.interface import shop_car_interface
from ATM购物车.interface import bank_interface
from ATM购物车.interface import admin_interface
import os
from ATM购物车.conf import settings


user_judge = {
    'username': '',
    'is_tage': False
}


def register():
    username = input('请输入你的用户名(q:退出):').strip()
    if username == 'q':
        return
    password = input('请输入你的密码:').strip()
    password_confirm = input('请再确认一下密码无误:').strip()
    if password != password_confirm:
        print('你两次密码输入不一致')
        return
    res = user_interface.register_interface(username, password)
    print(res)


is_tall = True


def login():
    global is_tall
    while is_tall:
        accept = common.random_verify()
        print(accept)
        verify = input('请输入你的验证码(q:退出):').strip()
        if verify == 'q':
            return
        if accept.upper() != verify.upper():
            print('验证码输入不正确,请重新输入')
            continue
        else:
            username = input('请输入你的用户名:').strip()
            password = input('请输入你的密码:').strip()
            if not password.isdigit():
                print('请输入纯数字')
                continue
            acct = user_interface.login_interface(username, password)
            if acct[2] == True:
                if user_judge.get('is_tage'):
                    print('你已经被冻结')
                    continue
            print(acct[0])
            is_tall = acct[1]


@common.outer
def addition():
    brevity_shop_car = {}
    while True:
        for i, j in enumerate(settings.GOOD_LIST, 1):
            print(f'''商品编号:{i}  |  商品名称:{j[0]}  |  商品价格:{j[1]}''')
        id = input('请输入你要购买商品的编号(q:退出):').strip()
        if id == 'q':
            shop_car_interface.add_write(brevity_shop_car, user_judge.get('username'))
            return
        if int(id) > len(settings.GOOD_LIST):
            print('没有该物品编号')
            continue
        number = input('请输入你想购买的个数:').strip()
        shop_car_interface.add_interface(settings.GOOD_LIST, id, number, brevity_shop_car, user_judge.get('username'))


@common.outer
def account():
    res = shop_car_interface.account_interface(user_judge.get('username'))
    print(res)


@common.outer
def reduce():
    while True:
        print('''
            1.删除商品
            2.减少个数
            3.退出业务
        ''')
        choice = input('请输入你的业务选择:').strip()
        if choice == '1':
            shop_car_interface.reduce_interface1(user_judge.get('username'))
        elif choice == '2':
            shop_car_interface.reduce_interface2(user_judge.get('username'))
        elif choice == '3':
            return
        else:
            print('没有该业务')


@common.outer
def transfer():
    while True:
        print('''
            1.充值
            2.转账
            3.退出
        ''')
        choice = input('请输入你的业务编号:').strip()
        if choice == '1':
            money = input('请输入你要充值的金额:').strip()
            if not money.isdigit():
                print('请输入纯数字')
                continue
            res = bank_interface.tr_bank_interface1(money, user_judge.get('username'))
            print(res)
        elif choice == '2':
            reduce_money = input('请输入你要转账的金额:').strip()
            if not reduce_money.isdigit():
                print('请输入纯数字')
                continue
            res = bank_interface.tr_bank_interface2(reduce_money, user_judge.get('username'))
            print(res)
        elif choice == '3':
            return
        else:
            print('没有该业务')


@common.outer
def look_shop_car():
    accept = shop_car_interface.look_shop_inter(user_judge.get('username'))
    new_shop_car = accept.get('shop_car')
    name = accept.get('username')
    for i, j in enumerate(new_shop_car):
        v = new_shop_car.get(j)
        print(f'''
        -----------------------------info------------------------------
        商品编号:{i}  *  商品名称:{j}  *  商品个数:{v[0]}  *  商品价格:{v[1]}
        ---------------------------------------------------------------
        ''')
    res = common.get_logger('查看购物车')
    res.debug(f'用户{name}查看了购物车')


@common.outer
def balance():
    accept = shop_car_interface.balance_inter(user_judge.get('username'))
    balance_money = accept[0].get('balance')
    name = accept[0].get('username')
    bank_money = accept[1].get('bank_card')  # 10000
    print(f'''
        -------------------money info-------------------\n
            你的购物卡余额为:{balance_money}\n
            你的银行卡余额为:{bank_money}\n
        ------------------------------------------------
        ''')
    res = common.get_logger('查看余额')
    res.debug(f'用户{name}查看了余额')


@common.outer
def operate_log():
    print('''
        1.查看购物车流水信息
        2.查看银行卡流水信息
        3.退出查看
    ''')
    choice = input('请输入你的查看选项:').strip()
    user_interface.operate_inter(choice)
    if choice == '3':
        return


@common.out
@common.outer
def admin():
    print('''
        1.冻结用户
        2.删除用户
        3.解除冻结
        4.查看指定用户的信息
        5.退出业务
    ''')
    choice = input('请你输入你的选择:').strip()
    if choice >= '6':
        print('没有该业务')
        return
    if choice == '5':
        return
    delete_admin = os.listdir(settings.File_path)  # ['gsy', 'lzq']
    for i, j in enumerate(delete_admin):
        print(f'''用户编号:{i}  |  用户名:{j}''')
    id = input('请输入你要(删除,冻结,解冻,查看)的用户编号:').strip()
    id1 = int(id)
    if id1 >= len(delete_admin):
        print('没有该用户')
        return
    if choice == '1':
        res = admin_interface.admin_interface1(delete_admin, id1, user_judge.get('username'))
        print(res)
    elif choice == '2':
        res = admin_interface.admin_interface2(delete_admin, id1)
        print(res)
    elif choice == '3':
        res = admin_interface.admin_interface3(delete_admin, id1)
        print(res)
    elif choice == '4':
        print('''
            1.查看该用户的的余额
            2.给该用户购物车充值
            3.查看该用户的账单
            4.查看该用户的购物车
            5.该用户的密码重置
        ''')
        change = input('请选择你的业务需求:').strip()
        res = admin_interface.admin_interface4(delete_admin, id1, change, user_judge.get('username'))
        print(res)


@common.outer
def roll_out():
    print('''
            1.购物车余额提现
            2.用户交互转账
            3.退出业务
        ''')
    choice = input('请你输入你的选择:').strip()
    if choice == '1':
        print('手续费是按照提现金额的%1收取')
        price = input('请输入你要提现的金额:').strip()
        res = bank_interface.roll_out_inter1(price, user_judge.get('username'))
        print(res)
    elif choice == '2':
        delete_admin = os.listdir(settings.File_path)  # ['gsy', 'lzq']
        for i, j in enumerate(delete_admin):
            print(f'''用户编号:{i}  |  用户名:{j}''')
        user_bank_id = input('请输入你要转入的用户名的编号:').strip()
        if int(user_bank_id) > len(delete_admin):
            print('用户编号不存在')
            return
        else:
            user_bank = delete_admin[int(user_bank_id)]
            shift_price = input('请输入你要转款的金额:').strip()
            shift_price = int(shift_price)
            res = bank_interface.roll_out_inter2(user_bank, shift_price, user_judge.get('username'))
            print(res)
    elif choice == '3':
        return
    else:
        print('没有该业务')


data = {'1': register, '2': login, '3': addition, '4': account, '5': reduce, '6': transfer, '7': look_shop_car,
        '8': balance, '9': operate_log, '10': admin, '11': roll_out}


def run():
    while True:
        print('''
            1.用户注册
            2.用户登录
            3.添加购物车
            4.结算购物车
            5.减少购物车
            6.充值与转账
            7.查看购物车
            8.查看余额
            9.查看流水
            10.管理员功能
            11.提现与相互转账
        ''')
        choice = input('请输入你的业务需求(q:退出):')
        if choice == 'q':
            print('拜拜了你嘞!')
            res = common.get_logger('退出')
            res.debug('退出程序')
            break
        elif choice in data:
            data.get(choice)()
        else:
            print('不好意思,没有该业务')

interface文件夹–接口层
user_interface.py–用户接口

from ATM购物车.lib import common
import os
from ATM购物车.conf import settings
from ATM购物车.core import src
from ATM购物车.database import db_handler

res = common.get_logger('用户信息')


def register_interface(username, password):
    username_path = os.path.join(settings.File_path, username)
    if os.path.exists(username_path):
        return f'用户名{username}已存在'
    res1 = common.get_md5(password)
    user_dict = {
        'username': username,
        'pwd': res1,
        'balance': 20000,
        'shop_car': {},
        'flow': [],  # 查看购物流水信息
        'is_tage': False,  # 信息是否冻结
        'is_admin': False  # 是否为管理员
    }
    bank_dict = {
        'username': username,
        'bank_card': 0,
        'flow': []
    }
    db_handler.register_db(user_dict, bank_dict)
    res.debug(f'用户{username}注册成功')
    return f'用户{username}注册成功'


def login_interface(username, password):
    acct = db_handler.select(username)
    if not acct:
        return '用户不存在', True, False
    pwd = common.get_md5(password)
    if pwd == acct.get('pwd'):
        src.user_judge['username'] = username
        src.user_judge['is_tage'] = acct.get('is_tage')
        res.debug(f'用户{username}登录成功!')
        return f'用户{username}登录成功!', False, True
    else:
        return '密码错误,请重新登录', True, False


def operate_inter(choice):
    if choice == '1':
        shop_operate_info = db_handler.select(src.user_judge.get('username'))  # 购物车信息
        shop_flow = shop_operate_info.get('flow')  # 操作流水列表
        if len(shop_flow) == 0:
            print('没有记录')
        else:
            for i, j in enumerate(shop_flow, 1):
                print(f'''流水步骤:{i}  |  执行内容:{j}''')
            res.debug(f'用户查看了购物车流水操作!')
    elif choice == '2':
        bank_operate_info = db_handler.select_bank(src.user_judge.get('username'))
        bank_flow = bank_operate_info.get('flow')
        if len(bank_flow) == 0:
            print('没有记录')
        else:
            for c, d in enumerate(bank_flow, 1):
                print(f'''流水步骤:{c}  |  执行内容:{d}''')
            res.debug(f'用户查看了银行流水操作!')
    else:
        print('没有该业务')

shop_car_interface.py–购物接口

from ATM购物车.lib import common
import os
from ATM购物车.conf import settings
from ATM购物车.database import db_handler
from ATM购物车.core import src

res = common.get_logger('购物车管理')


def add_interface(good_list, id, number, brevity_shop_car, username):  # {"挂壁面": [138, 3], "仿真玩偶": [1, 10000]}
    shop_info = db_handler.select(username)  # 购物车信息
    thing_info = good_list[int(id) - 1]  # ['挂壁面', 3]
    if thing_info[0] not in brevity_shop_car:
        brevity_shop_car.update({thing_info[0]: [int(number), thing_info[1]]})  # {'挂壁面': [2, 3]}
    else:
        number_price = brevity_shop_car.get(thing_info[0])  # [2, 3]
        single = number_price[0] + int(number)
        brevity_shop_car.update({thing_info[0]: [single, thing_info[1]]})
    print(brevity_shop_car)
    for name in brevity_shop_car:
        if name in shop_info.get('shop_car'):
            new_number = shop_info.get('shop_car')[name][0] + brevity_shop_car.get(name)[0]
            brevity_shop_car.update({name: [new_number, brevity_shop_car[name][1]]})
        else:
            shop_info['shop_car'].update({name: [int(number), thing_info[1]]})


def add_write(brevity_shop_car, username):
    shop_info = db_handler.select(username)  # 购物车信息
    shop_info['shop_car'].update(brevity_shop_car)
    user_path = os.path.join(settings.File_path, username)
    db_handler.shop_w_db(user_path, shop_info)
    shop_name = shop_info.get('username')
    res.debug(f'用户{shop_name}的购物车有{brevity_shop_car}')


def account_interface(username):
    accept = db_handler.select(username)  # 购物车信息
    shop_car = accept.get('shop_car')  # {"仿真玩偶": [1, 10000]}
    user_path = os.path.join(settings.File_path, username)
    sum = 0
    for i in shop_car:  # {"仿真玩偶": [1, 10000]}
        shop_list = shop_car.get(i)  # [1, 10000]
        sum = sum + (shop_list[0] * shop_list[1])
    if accept.get('balance') > sum:
        shop_car = {}
        accept['shop_car'] = shop_car
        new_money = accept.get('balance') - sum
        accept['balance'] = new_money
        accept.get('flow').append(f'你本次消费{sum}')
        db_handler.shop_w_db(user_path, accept)
        res.debug(f'用户{username}已结算购物车')
        return f'支付成功,你本次消费{sum},你的余额还有{new_money}'
    else:
        return '你的余额不足,请先充值'


def reduce_interface1(username):
    accept = db_handler.select(username)  # 购物车信息
    new_shop_info = accept.get('shop_car')  # {'仿真玩偶': [10, 10000], '挂壁面': [23, 3]}
    shop_info_list = list(new_shop_info.items())  # [('仿真玩偶', [10, 10000]), ('挂壁面', [23, 3])]
    if len(shop_info_list) == 0:
        change = input('你的购物车为空,是否购买(q/n):').strip()
        if change == 'q':
            src.addition()
            return
        else:
            return
    for i, j in enumerate(shop_info_list):
        print(f'商品编号:{i}  |  商品名称:{j[0]}  |  商品个数:{j[1][0]}  |  商品价格:{j[1][1]}')
    id = input('请输入你想删除商品的编号:').strip()
    if int(id) not in range(len(shop_info_list)):
        print('没有该物品编号')
        return
    if not id.isdigit():
        print('请输入纯数字')
        return
    shop_name = shop_info_list[int(id)]  # ('仿真玩偶', [10, 10000])
    new_shop_info.pop(shop_name[0])
    shop_info_list.pop(int(id))
    user_path = os.path.join(settings.File_path, username)
    db_handler.shop_w_db(user_path, accept)
    res.debug(f'商品{shop_name[0]}被删除')


def reduce_interface2(username):
    accept = db_handler.select(username)  # 购物车信息
    new_shop_info = accept.get('shop_car')  # {'仿真玩偶': [10, 10000], '挂壁面': [23, 3]}
    shop_info_list2 = list(new_shop_info.items())  # [('仿真玩偶', [10, 10000]), ('挂壁面', [23, 3])]
    if len(shop_info_list2) == 0:
        change = input('你的购物车为空,是否购买(q/n):').strip()
        if change == 'q':
            src.addition()
            return
        else:
            return
    for i, j in enumerate(shop_info_list2):
        print(f'商品编号:{i}  |  商品名称:{j[0]}  |  商品个数:{j[1][0]}  |  商品价格:{j[1][1]}')
    id1 = input('请输入你要减少物品的编号:').strip()
    if not id1.isdigit():
        print('请输入纯数字')
        return
    if int(id1) not in range(len(shop_info_list2)):
        print('没有该物品编号')
        return
    number = input('请输入你要减少的个数:').strip()
    if not number.isdigit():
        print('请输入纯数字')
        return
    shop_name1 = shop_info_list2[int(id1)]  # ('仿真玩偶', [10, 10000])
    new_number = shop_name1[1][0] - int(number)
    if new_number < 0:
        print('你还没有购买这么多')
        return
    if new_number == 0:
        new_shop_info.pop(shop_name1[0])
        shop_info_list2.pop(int(id1))
    else:
        new_shop_info[shop_name1[0]] = [new_number, shop_name1[1][1]]
    user_path = os.path.join(settings.File_path, username)
    db_handler.shop_w_db(user_path, accept)
    res.debug(f'商品{shop_name1[0]}被减少{number}')


def balance_inter(username):
    accept = db_handler.select(username)  # {'username': 'lzq', 'pwd': '123', 'balance': 20000, 'shop_car': {}}
    bank_accept = db_handler.select_bank(username)
    return accept, bank_accept


def look_shop_inter(username):
    accept = db_handler.select(username)
    return accept

bank_interface.py–银行接口

from ATM购物车.lib import common
from ATM购物车.database import db_handler
import os
from ATM购物车.conf import settings

res = common.get_logger('银行功能')


def tr_bank_interface1(money, username):
    accept = db_handler.select_bank(username)  # {"username": "lzq", "bank_card": 0}
    bank_money = accept.get('bank_card')
    # name = accept.get('username')
    new_bank_money = bank_money + int(money)
    accept['bank_card'] = new_bank_money
    accept.get('flow').append(f'用户{username}充值{int(money)}')
    db_handler.bank_w_db(username, accept)
    res.debug(f'用户{username}充值{money}')
    return f'你的银行卡余额为{new_bank_money}'


def tr_bank_interface2(reduce_money, username):
    db_info = db_handler.select(username)
    bank_info = db_handler.select_bank(username)
    bank_money = bank_info.get('bank_card')  # 10000
    # name = bank_info.get('username')
    if bank_money == 0:
        return '你的银行卡余额为0,请先充值'
    db_info['balance'] = db_info.get('balance') + int(reduce_money)  # 20000 + 5000
    bank_info['bank_card'] = bank_money - int(reduce_money)  # 10000 - 5000
    bank_reduce_money = bank_info.get('bank_card')
    db_info.get('flow').append(f'用户{username}转账{int(reduce_money)}')
    db_handler.shop_w_db(username, db_info)
    db_handler.bank_w_db(username, bank_info)
    res.debug(f'用户{username}转账{reduce_money}')
    return f'你的银行卡余额为{bank_reduce_money}'


def roll_out_inter1(price, username):  # 购物车往银行卡里转,还有手续费的收取
    price = int(price)
    username_path = os.path.join(settings.File_path, username)
    shop_roll_info = db_handler.select(username)  # 购物车信息
    shop_balance = shop_roll_info.get('balance')  # 购物车金额
    bank_roll_path = db_handler.select_bank(username)  # 银行卡信息
    bank_car_price = bank_roll_path.get('bank_card')  # 银行卡金额
    service_charge = price * settings.MONEY_RATE  # 手续费
    new_shop_balance = shop_balance - price - service_charge  # 购物车提现后的金额
    name = shop_roll_info.get('username')
    shop_roll_info.get('flow').append(f'用户{name}提现{price}')  # []
    shop_roll_info['balance'] = new_shop_balance
    db_handler.shop_w_db(username_path, shop_roll_info)
    new_bank_price = price + bank_car_price + service_charge  # 银行卡提现后的钱
    bank_roll_path['bank_card'] = new_bank_price
    res.debug(f'购物车余额为{new_shop_balance}')
    bank_path = os.path.join(settings.Bank_path, '%s.bank' % username)
    db_handler.shop_w_db(bank_path, bank_roll_path)
    return f'购物车余额为{new_shop_balance}, 银行卡余额为{new_bank_price}'


def roll_out_inter2(user_bank, shift_price, username):  # 输入的用户名  转款金额
    name = username
    if name == user_bank:
        return '不能给自己转账哦'
    else:
        shop_roll_path = db_handler.select(user_bank)  # 被转款人购物车信息
        shop_balance = shop_roll_path.get('balance')  # 被转款人购物车金额
        my_shop_info = db_handler.select(name)  # 转款人购物车信息
        my_shop_price = my_shop_info.get('balance')  # 转款人购物车金额
        new_shop_balance = shift_price + shop_balance  # 转款后金额
        shop_roll_path['balance'] = new_shop_balance
        username_path = os.path.join(settings.File_path, user_bank)
        db_handler.shop_w_db(username_path, shop_roll_path)
        new_my_price = my_shop_price - shift_price
        my_shop_info['balance'] = new_my_price
        my_price_path = os.path.join(settings.File_path, username)
        my_name = my_shop_info.get('username')
        shop_name = shop_roll_path.get('username')
        my_shop_info.get('flow').append(f'用户{my_name}向用户{shop_name}转账{shift_price}')
        db_handler.shop_w_db(my_price_path, my_shop_info)
        res.debug(f'用户{name}{user_bank}转款{shift_price}')
        return f'用户{name}购物车余额为{new_my_price}, 用户{user_bank}购物车余额为{new_shop_balance}'

admin_interface.py-管理员接口

from ATM购物车.lib import common
import os
from ATM购物车.conf import settings
from ATM购物车.database import db_handler

res = common.get_logger('管理员功能')


def admin_interface2(delete_admin, id1):
    name = delete_admin[id1]
    delete_name_path = os.path.join(settings.File_path, name)  # D:\pythonProject\day29\ATM购物车\conf\db\lzq
    delete_bank_path = os.path.join(settings.Bank_path, '%s.bank' % name)
    if os.path.exists(delete_name_path):
        os.remove(delete_name_path)
        os.remove(delete_bank_path)
        res.info(f'用户{name}已被管理员删除')
        return f'用户{name}已删除'
    else:
        return f'用户不存在'


def admin_interface1(delete_admin, id1, username):
    name = delete_admin[id1]
    if username == name:
        return '不可以冻结自己哦'
    else:
        freeze_path = os.path.join(settings.File_path, name)
        accept = db_handler.select(name)  # 购物车信息
        accept['is_tage'] = True
        db_handler.shop_w_db(freeze_path, accept)
        res.info(f'用户{name}被冻结!')
        return f'用户{name}已被冻结'


def admin_interface3(delete_admin, id1):
    name = delete_admin[id1]
    freeze_path = os.path.join(settings.File_path, name)
    accept = db_handler.select(name)  # 购物车信息
    accept['is_tage'] = False
    db_handler.shop_w_db(freeze_path, accept)
    res.info(f'用户{name}已解冻!')
    return f'用户{name}已被解冻'


def admin_interface4(delete_admin, id1, change, username):
    name = delete_admin[id1]
    if change == '1':
        user_dict = db_handler.select(name)
        bank_dict = db_handler.select_bank(name)
        print(f'''
        ******************info*******************
        购物车余额:{user_dict.get('balance')}  |  银行卡余额:{bank_dict.get('bank_card')}
        *****************************************
        ''')
        res.info(f'已显示{name}余额')
        return f'已显示{name}余额'
    elif change == '2':
        user_dict = db_handler.select(name)
        balance_money = user_dict.get('balance')
        increase = input('请输入你要充值的金额:').strip()
        increase = float(increase)
        user_dict['balance'] = balance_money + increase
        user_dict.get('flow').append(f'用户{username}向用户{name}充值了{increase}')
        db_handler.shop_w_db(name, user_dict)
        res.info(f'用户{username}向用户{name}充值了{increase}')
        return f'用户{username}向用户{name}充值了{increase}'
    elif change == '3':
        user_dict = db_handler.select(name)
        bank_dict = db_handler.select_bank(name)
        print(f'''
        ******************info*******************
        购物车账单:{user_dict.get('flow')}  |  银行卡账单:{bank_dict.get('flow')}
        *****************************************
            ''')
        res.info(f'已显示{name}账单')
        return f'已显示{name}账单'
    elif change == '4':
        user_dict = db_handler.select(name)
        print(f'''
        ******************info*******************
        购物车账单:{user_dict.get('shop_car')}
        *****************************************
            ''')
        res.info(f'已显示{name}购物车信息')
        return f'已显示{name}购物车信息'
    elif change == '5':
        user_dict = db_handler.select(name)
        old_pwd = input('请输入你的旧密码:').strip()
        res1 = common.get_md5(old_pwd)
        if res1 != user_dict.get('pwd'):
            return '密码不正确'
        new_pwd = input('请输入你的新密码:').strip()
        again_pwd = input('请再一次输入你的密码:').strip()
        if new_pwd != again_pwd:
            return print('新密码不一致')
        res1 = common.get_md5(new_pwd)
        user_dict['pwd'] = res1
        db_handler.shop_w_db(name, user_dict)
        res.info(f'用户{name}的密码已改为{res1}')
        return f'用户{name}的密码已改为{res1}'
    else:
        return '没有该业务'
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值