ATM+购物车
conf 存放配置文件的文件夹
__ init __.py
settings.py
import os
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
DB_PATH = os.path.join(BASE_PATH, 'db')
'''
日志配置
'''
# 定义三种日志输出格式 开始
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'
id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
# 定义日志输出格式 结束
logfile_dir = os.path.join(BASE_PATH, 'log') # log文件的目录
logfile_name = 'atm_shop_log.log' # log文件名
# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
os.mkdir(logfile_dir)
# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)
# 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', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'level': 'DEBUG',
'propagate': True, # 向上(更高level的logger)传递
},
},
}
core 存放核心代码的文件夹
__ init __ .py
src.py
from db import db_handler
from lib import common
import re
from interface import user_interface
from interface import bank_interface
from interface import shop_interface
user_info = {
'user': None
}
# 注册功能
def register():
while True:
username = input('请输入用户名:').strip()
if username == 'q':
break
if not re.search(u'^[_a-zA-Z0-9\u4e00-\u9fa5]+$', username):
print('用户名中只能包含汉字,字母,数字,下划线!')
continue
if db_handler.check_data(username):
print('该用户已经存在!')
continue
password = input('请输入密码:').strip()
if password == 'q' or password == '':
break
re_password = input('请再次输入密码:').strip()
if re_password == 'q' or re_password == '':
break
if password == re_password:
msg = user_interface.register_interface(username, password)
print(msg)
break
else:
print('两次密码输入不一致')
# 登录功能
def login():
while True:
if user_info['user']:
print('您已经登录,请先注销!')
break
username = input('请输入用户名:').strip()
if username == 'q':
break
if db_handler.check_data(username):
password = input('请输入密码:').strip()
if password == 'q':
break
flag, msg = user_interface.login_interface(username, common.get_md5(password))
if flag:
print(msg)
user_info['user'] = username
break
else:
print(msg)
continue
else:
print('该用户不存在!')
continue
# 查看余额功能
@common.wrapper
def check_bal():
msg = user_interface.check_bal_interface(user_info['user'])
print(f'当前余额为{msg}!')
# 转账功能
@common.wrapper
def transfer():
while True:
to_user = input('请输入要转账的对象:').strip()
if to_user == 'q':
break
if not db_handler.check_data(to_user):
print('该用户不存在!')
continue
if to_user == user_info['user']:
print('还想转给自己!')
continue
money = input('请输入要转账的金额:').strip()
if money == 'q':
break
if not money.isdigit():
print('请输入整数金额!')
continue
flag, msg = bank_interface.transfer_interface(user_info['user'], to_user, money)
if flag:
print(msg)
break
else:
print(msg)
break
# 提现功能
@common.wrapper
def withdraw():
while True:
money = input('请输入要提现的金额:').strip()
if money == 'q':
break
if not money.isdigit():
print('输入整数金额!')
continue
flag, msg = bank_interface.withdraw_interface(user_info['user'], money)
if flag:
print(msg)
break
else:
print(msg)
break
# 还款功能
@common.wrapper
def repay():
while True:
money = input('请输入要还款的金额:').strip()
if money == 'q':
break
if not money.isdigit():
print('请输入整数金额!')
continue
msg = bank_interface.repay_interface(user_info['user'], money)
print(msg)
break
# 查看购物车
@common.wrapper
def check_shop_cart():
flag, msg = shop_interface.check_shop_cart(user_info['user'])
if flag:
print(msg)
else:
print(msg)
# 购物功能
@common.wrapper
def shopping():
cost = 0
shop_cart = {}
while True:
shop_info = [
['tank牌香水', 1200],
['tank写真集', 1],
['怡宝', 4],
['百岁山', 6],
['劳斯莱斯', 2400000],
]
for shop_num, name_and_price in enumerate(shop_info):
print(
f'商品编号:{shop_num}',
f'商品名称:{name_and_price[0]}',
f'商品价格: {name_and_price[1]}',
)
choice = input('请选择商品编号:').strip()
if choice == 'q':
break
if choice.isdigit() and int(choice) < len(shop_info):
current_bal = user_interface.check_bal_interface(user_info['user'])
shop_name, shop_price = shop_info[int(choice)]
if current_bal >= shop_price:
if shop_name in shop_cart:
shop_cart[shop_name] += 1
else:
shop_cart[shop_name] = 1
cost += shop_price
choice1 = input('q退出,任意键继续购物').strip()
if choice1 == 'q':
commit = input('是否结账:"Y"or"N":').strip()
if commit == 'Y':
flag, msg = shop_interface.pay_interface(user_info['user'], cost)
if flag:
print(msg)
break
else:
print(msg)
msg1 = shop_interface.add_shop_cart(user_info['user'], shop_cart)
print(msg1)
break
elif commit == "N":
msg = shop_interface.add_shop_cart(user_info['user'], shop_cart)
print(msg)
break
else:
print('请输入合法的指令!')
continue
else:
print('您的余额太少还是去充值吧!')
break
else:
print('请输入合法额指令!')
continue
# 查看流水
@common.wrapper
def check_flow():
flag, msg = user_interface.check_flow_interface(user_info['user'])
if flag:
for line in msg:
print(line)
else:
print(msg)
# 注销
@common.wrapper
def cancel():
msg = user_interface.cancel_interface()
print(msg)
# 功能函数字典
func_dict = {
'1': register,
'2': login,
'3': check_bal,
'4': transfer,
'5': withdraw,
'6': repay,
'7': check_shop_cart,
'8': shopping,
'9': check_flow,
'10': cancel,
}
# 执行程序
def run():
while True:
print('''
*******功能主界面*****
1.注册
2.登录
3.查看余额
4.转账
5.提现
6.还款
7.查看购物车
8.购物功能
9.查看流水
10.注销
ps:任意输入界面输入'q'返回至主界面
主界面位置输入'Q'退出程序
''')
choice = input('请输入要选择的功能对应的编号:').strip()
if choice == 'Q':
break
if choice.isdigit() and 0 < int(choice) < len(func_dict) + 1:
choice = str(choice)
func_dict[choice]()
else:
print('请输入有效的指令!')
db 存放数据的文件夹,相当于数据库
__ init __.py
db_handler.py
from conf import settings
import os
import json
# 查看数据
def check_data(user):
user_path = os.path.join(settings.DB_PATH, f'{user}.json')
if os.path.exists(user_path):
with open(user_path, 'r', encoding='utf-8') as f:
user_dict = json.load(f)
f.flush()
return user_dict
else:
return False
# 保存数据
def save_data(user_dict):
user_path = os.path.join(settings.DB_PATH, f'{user_dict["user"]}.json')
with open(user_path, 'w', encoding='utf-8')as f:
json.dump(user_dict, f, ensure_ascii=False)
f.flush()
interface 存放接口的文件夹
__ init __.py
bank_interface.py
from db import db_handler
from lib import common
bank_logger = common.get_logger('bank')
# 转账接口
def transfer_interface(my_user, to_user, money):
my_user_dict = db_handler.check_data(my_user)
to_user_dict = db_handler.check_data(to_user)
if my_user_dict['balance'] >= int(money):
my_user_dict['balance'] -= int(money)
to_user_dict['balance'] += int(money)
flow_str1 = f'{my_user}给{to_user}转了{money}元!'
flow_str2 = f'{to_user}接收了{my_user}{money}元!'
my_user_dict['flow'].append(flow_str1)
to_user_dict['flow'].append(flow_str2)
db_handler.save_data(my_user_dict)
db_handler.save_data(to_user_dict)
bank_logger.info(f'{my_user}进行了转账操作!')
return True, '转账成功!'
else:
return False, '余额不足无法转账!'
# 提现接口
def withdraw_interface(user, money):
user_dict = db_handler.check_data(user)
if user_dict['balance'] >= int(money):
user_dict['balance'] -= int(money) * 1.05
flow_str = f'{user}提现{money}元,手续费{int(money) * 0.05}'
user_dict['flow'].append(flow_str)
db_handler.save_data(user_dict)
bank_logger.info(f'{user}进行了提现操作!')
return True, f'{user}提现{money}元成功!,手续费{int(money) * 0.05}'
else:
return False, '余额不足,提现失败'
# 还款接口
def repay_interface(user, money):
user_dict = db_handler.check_data(user)
user_dict['balance'] += int(money)
flow_str = f'{user}还款{money}元成功!'
user_dict['flow'].append(flow_str)
db_handler.save_data(user_dict)
bank_logger.info(f'{user}进行了还款操作!')
return f'{user}还款{money}元成功!'
shop_interface.py
from db import db_handler
from lib import common
shop_logger = common.get_logger('shop')
# 支付接口
def pay_interface(user, cost):
user_dict = db_handler.check_data(user)
if user_dict['balance'] >= int(cost):
user_dict['balance'] -= int(cost)
flow_str = f'{user}购买商品成功!花费{cost}元!'
user_dict['flow'].append(flow_str)
db_handler.save_data(user_dict)
shop_logger.info(f'{user}购买了商品!')
return True, '购买成功!'
else:
return False, '余额不足,购买失败!'
# 查看购物车接口
def check_shop_cart(user):
user_dict = db_handler.check_data(user)
if user_dict['shop_cart']:
return True, user_dict['shop_cart']
else:
return False, '目前购物车为空!'
# 添加购物车接口
def add_shop_cart(user, shop_cart):
user_dict = db_handler.check_data(user)
user_dict['shop_cart'].update(shop_cart)
db_handler.save_data(user_dict)
return '已自动帮您添加到购物车,方便你下次选购!'
user_interfcae.py
from db import db_handler
from lib import common
user_logger = common.get_logger('user')
# 注册接口
def register_interface(user, pwd):
user_dict = {
'user': user,
'pwd': common.get_md5(pwd),
'balance': 20000,
'flow': [],
'shop_cart': {},
'lock': False,
}
db_handler.save_data(user_dict)
user_logger.info(f'{user}注册成功!')
return f'{user}注册成功!'
# 登录接口
def login_interface(user, pwd):
user_dict = db_handler.check_data(user)
if user_dict['pwd'] == pwd:
user_logger.info(f'{user}登录成功!')
return True, f'{user}登录成功!'
else:
return False, f'密码不正确!'
# 查看余额接口
def check_bal_interface(user):
user_dict = db_handler.check_data(user)
return user_dict['balance']
# 查看流水接口
def check_flow_interface(user):
user_dict = db_handler.check_data(user)
if user_dict['flow']:
return True, user_dict['flow']
else:
return False, '还没有流水'
# 注销接口
def cancel_interface():
from core import src
src.user_info['user'] = None
user_logger.info(f'注销成功!')
return '注销成功!'
lib 存放公共方法的文件夹
__ init __
common.py
import hashlib
import logging.config
from conf import settings
# 密码加密
def get_md5(pwd):
obj_md5 = hashlib.md5()
obj_md5.update(pwd.encode('utf-8'))
sal = '超喜欢你!'
obj_md5.update(sal.encode('utf-8'))
res = obj_md5.hexdigest()
return res
# 登录认证的装饰器
def wrapper(func):
from core import src
def inner(*args, **kwargs):
if src.user_info['user']:
res = func(*args, **kwargs)
return res
else:
print('请先进行登录操作!')
src.login()
return inner
# 日志功能
def get_logger(user_type):
logging.config.dictConfig(settings.LOGGING_DIC)
logger = logging.getLogger(user_type)
return logger
log 存放日志的文件夹
readme.txt 项目说明书
1.注册
2.登录
3.查看余额
4.提现
5.还款
6.转账
7.查看购物车
8.购物功能
9.查看流水
10.注销
start.py 启动文件
import os
import sys
from core import src
# 配置环境变量
sys.path.append(
os.path.dirname(__file__)
)
if __name__ == '__main__':
src.run()