目录
这个小项目很好的结合了前面所学的知识,能帮助我们回复巩固前面学习的基础知识,又能训练编码能力!
start.py
import sys
from conf import setting
from core import src
sys.path.append(setting.BASE_PATH)
if __name__ == '__main__':
src.run()
setting.py
import os
import logging.config
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
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'
log_file_path = os.path.join(BASE_PATH, 'log', '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': log_file_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)传递
}, # 当键不存在的情况下 (key设为空字符串)默认都会使用该k:v配置
},
}
src.py
"""
1、注册
2、登录
3、查看余额
4、转账
5、提现
6、还款
7、查看流水
8、购物
9、加入购物车
"""
import time
from lib import common
from intetface import user, bank, shopping_cart
from collections import OrderedDict
# 退出
def log_out():
name_list.clear()
# 注册
def register():
while True:
inp_name = input('请输入你的姓名:').strip()
user_dict = common.read_file(inp_name)
if user_dict:
print('该用户信息已存在!!!\n')
continue
inp_password = input('请输入你的密 码:').strip()
re_password = input('请再次输入你的密码:').strip()
if inp_password == re_password:
user.regirset(inp_name, inp_password)
print('注册成功!')
break
else:
print('两次密码输入不一致')
# 登录
def login():
count = 0
while True:
inp_name = input('请输入你的用户名(退出输入q):').strip()
if inp_name == 'q':
break
# 使路径能用在全局
user_dict = common.read_file(inp_name)
# 判断有没有该用户文件
if not user_dict:
print('该用户不存在,请重新输入!!!\n')
continue
inp_pwd = input('请输入你的密码:').strip()
# 如果错误次数超过3次就封锁账号
if count > 2:
user_dict['locked'] = True
common.write_file(user_dict)
break
# 判断该账户是否被锁定
if user_dict['locked']:
print('该账户已被锁定!!!')
break
# 校验账号密码
inp_pwd = common.hashlib_pwd(inp_pwd)
if user_dict['username'] == inp_name and user_dict['password'] == inp_pwd:
print('登录成功!')
name_list.append(user_dict)
logger1 = common.write_loggers('登录功能')
logger1.info('%s 登录成功' % inp_name)
return login_after()
else:
print('账户或密码错误!!!')
count += 1
# 查看余额
def check_balance():
print('您的余额为:%s' % name_list[0]['balance'])
# 转账
def transfer():
while True:
tsf_name = input('请输入转入用户用户名>>>:').strip()
to_user_dict = common.read_file(tsf_name)
# 判断有没有该用户文件
if not to_user_dict:
print('该用户不存在,请重新输入!!!\n')
continue
user_dict = name_list[0]
inp_money = input('请输入转账金额:').strip()
# 判断输入是否是正确的金额
if not inp_money.isdigit():
print('请输入正确的金额!!!')
continue
money = int(inp_money)
# 判断账户余额是否足够
if user_dict['balance'] < money:
print('账户余额不足!!!')
continue
bank.transfer(user_dict, to_user_dict, money)
print('转账成功!!!\n ')
break
# 取款
def withdraw():
while True:
money = input('请输入您的提现金额:').strip()
if not money.isdigit():
print('请输入正确的金额!!!')
continue
money = int(money)
# 判断额度
if money > 20000:
print('您的额度不够!!!')
continue
user_dict = name_list[0]
# 判断余额
if money > user_dict['balance']:
print('您的余额不足!!!')
continue
bank.withdraw(user_dict, money)
print('提现成功!!!\n')
break
# 充钱
def repay():
while True:
money = input('请输入充值金额>>>:').strip()
if not money.isdigit():
print('请输入正确的金额!!!\n')
continue
money = int(money)
if money < 10:
print('充值金额太少,要不你拿回去买泡面吃算了!!!\n')
user_dict = name_list[0]
bank.repay(user_dict, money)
print('充值成功!!!')
break
# 查看流水
def check_flow():
res = name_list[0]['bank_flow']
for i in res:
print(i)
# 查看购物车
def shopping():
user_dict = name_list[0]
if not user_dict['shopping']:
print('您的购物车为空!!!')
return
for i in user_dict['shopping']:
print(f'商品名称:{i[0]}, 单价:{i[1]}, 数量{i[2]}, 总价{i[1] * i[2]}')
print()
# 添加购物车
def add_shopping():
while True:
goods_list = [
["car", 1000],
["tea", 200],
["coffee", 500],
]
for i, j in enumerate(goods_list):
name, price = goods_list[i]
print(f'{(i + 1)} 商品名称:{name} 单价{price}')
print('0 : 退出\n')
choice = input('请输入你的选择>>:').strip()
if choice == '0':
break
if not choice.isdigit():
print('请输入正确的编号!!!\n')
continue
if int(choice) > len(goods_list):
print('请输入正确的编号!!!\n')
continue
while True:
count = input('请输入购买数量!!!\n').strip()
if not count.isdigit():
print('请输入正确的数量!!!\n')
continue
count = int(count)
good_list = goods_list[int(choice) - 1]
user_dict = name_list[0]
res = shopping_cart.add_shopping_cart(user_dict, good_list, count)
if res:
print('商品%s添加成功!!!\n' % good_list[0])
break
print('余额不足,请重新输入!!!\n')
name_list = []
# 有序字典
func_dic1 = OrderedDict([('1', ['注册', register]), ('2', ['登录', login]), ('0', ['退出', log_out])])
func_dic2 = OrderedDict([('1', ['查看余额', check_balance]), ('2', ['转账', transfer]), ('3', ['提现', withdraw]),
('4', ['充值', repay]), ('5', ['查看流水', check_flow]), ('6', ['查看购物车', shopping]),
('7', ['加入购物车', add_shopping]), ('0', ['退出', log_out])])
def run():
while True:
for i in func_dic1:
print(f'{i}--->{func_dic1[i][0]}')
choice = input('请输入序号:').strip()
if not choice:
print('请输入序号!!!\n')
continue
if choice not in func_dic1:
print('请输入正确的序号\n')
continue
if choice == '0':
break
else:
func_dic1[choice][1]()
def login_after():
while True:
for i in func_dic2:
print(f'{i}--->{func_dic2[i][0]}')
choice = input('请输入序号:').strip()
if not choice:
print('请输入序号!!!\n')
continue
if choice not in func_dic2:
print('请输入正确的序号\n')
continue
func_dic2[choice][1]()
time.sleep(0.5)
if choice == '0':
break
user.py
from lib import common
# 注册
def regirset(username, password, path_file):
password = common.hashlib_pwd(password)
user_dict = {
'username': username,
'password': password,
'balance': 10000,
'shopping': [],
'title': 'user',
'locked': False,
'bank_flow': []
}
logger1 = common.write_loggers('注册功能')
logger1.info('%s 注册成功' % username)
common.write_file(path_file, user_dict)
bank.py
import datetime
from lib import common
# 转账
def transfer(user_dict, to_user_dict, money):
# 获取时间
tm = datetime.datetime.today()
# 记录转账用户信息
user_dict['balance'] = user_dict['balance'] - money
res1 = '%s 给 %s 转账 %s' % (tm, to_user_dict['username'], money)
user_dict['bank_flow'].append(res1)
common.write_file(user_dict)
# 记录接收用户信息
res2 = '%s 接收 %s 转账 %s' % (tm, user_dict['username'], money)
to_user_dict['balance'] = to_user_dict['balance'] + money
to_user_dict['bank_flow'].append(res2)
common.write_file(to_user_dict)
# 记录日志
res3 = '%s 给 %s 转账 %s' % (user_dict['username'], to_user_dict['username'], money)
loger = common.write_loggers('转账记录')
loger.info(res3)
# 取款
def withdraw(user_dict, money):
money1 = user_dict['balance'] - money
user_dict['balance'] = money1
tm = datetime.datetime.today()
res = '%s: 取款 %s' % (tm, money)
user_dict['bank_flow'].append(res)
common.write_file(user_dict)
# 日志
logger1 = common.write_loggers('取款功能')
logger1.info('%s 提现 %s 元' % (user_dict['username'], money))
# 充值
def repay(user_dict, money):
money1 = user_dict['balance'] + money
user_dict['balance'] = money1
tm = datetime.datetime.today()
user_dict['bank_flow'].append('%s: 充值 %s' % (tm, money))
common.write_file(user_dict)
# 日志
logger = common.write_loggers('充值功能')
logger.info('%s 充值 %s 元' % (user_dict['username'], money))
shopping_cart.py
import datetime
from lib import common
def add_shopping_cart(user_dict, good_list, count):
name, price = good_list
money = price * count
# 判断余额是否充足
if money > user_dict['balance']:
return False
# 判断购物车里是否已经存在该商品
for i in user_dict['shopping']:
if name in i:
# 存在即在购物车里面就加购
i[2] += count
break
else:
# 不存在就把商品信息和数量加入购物车
good_list.append(count)
user_dict['shopping'].append(good_list)
# 账户扣款
user_dict['balance'] = user_dict['balance'] - money
common.write_file(user_dict)
# 添加流水记录
tm = datetime.datetime.today()
res1 = '%s: 购物(%s)花费: %s' % (tm, name, money)
user_dict['bank_flow'].append(res1)
common.write_file(user_dict)
# 添加日志
logger = common.write_loggers('购物功能')
logger.info('%s 购物(%s)花费: %s' % (user_dict['username'], name, money))
return True
common.py
import hashlib
import os
import json
from conf import setting
import logging
import logging.config
# 验证用户是否存在, 存在则读取文件
def read_file(username):
path_file = os.path.join(setting.BASE_PATH, 'db', '%s.json' % username)
if os.path.exists(path_file):
with open(path_file, 'r', encoding='utf8') as f:
user_dict = json.load(f)
return user_dict, path_file
return False, path_file
# 写入文件
def write_file(path_file, user_dict):
with open(path_file, 'w', encoding='utf8') as f:
json.dump(user_dict, f, ensure_ascii=False)
f.flush()
# 密码加密
def hashlib_pwd(password):
m5 = hashlib.md5()
m5.update(password.encode('utf8'))
res = m5.hexdigest()
return res
# 日志写入
def write_loggers(auth):
logging.config.dictConfig(setting.LOGGING_DIC) # 自动加载字典中的配置
logger1 = logging.getLogger(auth)
return logger1