2020/6/19 ATM+购物商城(自己写的)

写该程序时还对os,sys等模块不熟悉,导致代码内有多余或错误的路径添加,对from import也不熟悉,也是有很多的错误存在,虽然功能都能够实现,但是代码有些辣眼睛。

一下为各个文件内的内容

目录:

 

ATM代码:

atm.py

import os
import sys

BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_PATH)

from core import main

main.main()

 

accounts.py

#用于从文件里加载和存储账户数据

import db_handler
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
print(BASE_DIR)


from ATM.db import account_sample

def user_read(user_id):
    #加载用户数据
    data = account_sample.account_read(user_id)
    return data

def user_reload(user_info):
    #重载用户信息
    account_sample.account_load(user_info)

 

 

auth.py

import accounts
import logger

#用户认证模块

def user_login(func):
    #用户认证登录
    def Authentication():
        try:
            user_id = int(input("请输入您的ID:"))
            password = input("请输入您的密码:")
            data = accounts.user_read(user_id)
            if data["password"] == password:
                print('%s,欢迎您的登录'%(data['user_name']))
                logger.user_login_log(user_id,data['user_name'])
                return func(user_id)
            else:
                print("您输入的密码有误")
        except FileNotFoundError:
            print("您所输入的用户ID不存在")
    return Authentication

 

db_handler.py

import os
import sys

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

 

logger.py

import time
import os

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

localtime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())

def user_login_log(user_id,user_name):
    #用户登录日志
    with open(r'%s\logs\access.log' %BASE_DIR,'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 进行了登录操作。\n" %(localtime,user_id,user_name))

def user_save_money_log(user_id,user_name,amount):
    #用户存款日志
    with open("../logs/access.log",'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 进行了存款操作。\n" %(localtime,user_id,user_name))

    with open("../logs/transactions.log",'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 存入%d元。\n" %(localtime,user_id,user_name,amount))

def user_draw_money_log(user_id,user_name,amount):
    #用户取款日志
    with open("../logs/access.log",'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 进行了取款操作。\n" %(localtime,user_id,user_name))

    with open("../logs/transactions.log",'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 取出%d元。\n" %(localtime,user_id,user_name,amount))

def user_pay_log(user_id,user_name,amount):
    #用户消费日志
    with open(r'%s\logs\access.log' %BASE_DIR,'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 在京猫商城进行了消费。\n" %(localtime,user_id,user_name))

    with open(r'%s\logs\transactions.log' %BASE_DIR,'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 消费了%d元。\n" %(localtime,user_id,user_name,amount))

def user_check_balance_log(user_id,user_name):
    #用户查余额日志
    with open("../logs/access.log",'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 进行了查余额操作。\n" %(localtime,user_id,user_name))

def user_transfer_accounts_log(user_id,user_name,transfer_id,amount):
    #用户转账日志
    with open("../logs/access.log",'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 进行了转账操作。\n" %(localtime,user_id,user_name))

    with open("../logs/transactions.log",'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 给ID:%d 转账%d元。\n" %(localtime,user_id,user_name,transfer_id,amount))

def user_logout_log(user_id,user_name):
    #用户登出日志
    with open("../logs/access.log",'a',encoding='utf-8') as f:
        f.write("%s 用户ID:%d 用户名:%s 退出了登录。\n" %(localtime,user_id,user_name))

 

main.py

import os
import sys

BASE_DIR=os.path.dirname(__file__)
sys.path.append(BASE_DIR)
import transaction
import auth
import accounts
import logger

@auth.user_login
def main(user_id):
    while True:
        user_info = accounts.user_read(user_id)
        print('可操作列表'.center(50,"*"),"\n1.存款\n2.取款\n3.余额查询\n4.转账")
        user_choice = input("请选择您要执行的操作:")
        if user_choice == "1":
            amount = int(input("存多少:"))
            transaction.save_money(user_info,amount)
        elif user_choice == "2":
            amount = int(input("取多少:"))
            transaction.draw_money(user_info,amount)
        elif user_choice == "3":
            transaction.check_balance(user_info)
        elif user_choice == "4":
            transfer_id = int(input("请输入您要转账的ID:"))
            amount = int(input("请输入您要转账的金额:"))
            transaction.transfer_accounts(user_info,transfer_id,amount)
        elif user_choice == "q":
            logger.user_logout_log(user_id,user_info["user_name"])
            break

 

transaction.py

#相关操作模块
import os
import sys
BASE_DIR=os.path.dirname(__file__)
sys.path.append(BASE_DIR)

import accounts
import os
import logger

def save_money(account_info,amount):
    #存款
    data = account_info
    data["user_balance"] += amount
    accounts.user_reload(data)
    logger.user_save_money_log(data['user_id'],data['user_name'],amount)
    print("存款成功,您现在的余额为%s" % (data["user_balance"]))

def draw_money(account_info,amount):
    #取款
    data = account_info
    if amount <= account_info["user_balance"]:
        data["user_balance"] -= amount
        accounts.user_reload(data)
        logger.user_draw_money_log(data['user_id'], data['user_name'], amount)
        print("取款成功,您现在的余额为%s" %(data["user_balance"]))
    else:
        print("您的余额不足")

def pay(account_info,amount):
    #付款
    data = account_info
    if amount <= account_info["user_balance"]:
        data["user_balance"] -= amount
        accounts.user_reload(data)
        logger.user_pay_log(data['user_id'], data['user_name'], amount)
        print("购买成功,您现在的余额为%s" % (data["user_balance"]))
    else:
        print("您的余额不足")

def check_balance(account_info):
    #查询余额
    data = account_info
    logger.user_check_balance_log(data['user_id'], data['user_name'])
    print("您的余额为:%s" %(data["user_balance"]))

def transfer_accounts(account_info,transfer_id,amount):
    #转账
    data = account_info
    file_list = os.listdir("../db/accounts")
    if "%s.json"%(transfer_id) in file_list:
        transfer_data = accounts.user_read(transfer_id)
        if data["user_id"] == transfer_data["user_id"]:
            print("您不能给自己转账")
        else:
            if account_info["user_balance"] < amount:
                print("您没有足够的钱")
            else:
                account_info["user_balance"] -= amount
                transfer_data["user_balance"] += amount
                accounts.user_reload(account_info)
                accounts.user_reload(transfer_data)
                logger.user_transfer_accounts_log(data['user_id'], data['user_name'],transfer_id,amount)
                print("您成功向ID:%s转账%d元,您当前的余额为%d"%(transfer_id,amount,account_info["user_balance"]))
    else:
        print("您要转账的对象不存在")

 

accounts_sample.py

import os
import sys
import json

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

sys.path.append(BASE_DIR)

def account_load(user_info):
    #重载用户信息
    with open(r'%s\accounts\%d.json' % (BASE_DIR, user_info['user_id']), "w") as f:
        json.dump(user_info, f)

def account_read(account_id):
    #读取用户信息
    with open(r'%s\accounts\%d.json' % (BASE_DIR, account_id), "r") as f:
        data = json.load(f)
        return data

 

 

shopping_mall代码:

shopping_mall.py

import os,sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


from core import main

main.go_shoppping()

 

main.py

import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR2=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
sys.path.append(BASE_DIR2)


from db import shoppingmange
from ATM.core import transaction
from ATM.core import auth
from ATM.core import accounts

product_dict = shoppingmange.show_shopping()

shopping_car=[]
count = 0

@auth.user_login
def go_shoppping(user_id):
    #购物
    user_info = accounts.user_read(user_id)
    print(user_info)
    exit_flag = False
    flag1 = False
    while not exit_flag:
        print('欢迎来到京猫商城'.center(30,'*'))
        for showshopping in product_dict:   #遍历字典
            print(showshopping)             #打印字典的key(商品种类)
        user_choice = input('请输入你要购买的商品种类:')
        if user_choice == 'q':
            closing(shopping_car)
            exit_flag = True
        else:
            while not exit_flag:
                if not flag1 :
                    for type_choice in product_dict:    #遍历字典
                        if user_choice == type_choice:  #判断用户的选择
                            for index,shopping_list in enumerate(product_dict[type_choice]):    #打印用户选择的种类里的产品
                                print(index,'%s %d元' %(shopping_list[0],shopping_list[1]))
                            choice_shopping = input('请输入你要购买的商品:')
                            if choice_shopping.isdigit():
                                choice_shopping = int(choice_shopping)
                                for index, shopping_list in enumerate(product_dict[type_choice]):
                                    if choice_shopping == index:
                                        shopping_car.append(shopping_list)
                                print(shopping_car)
                            elif choice_shopping == 'q':
                                closing(shopping_car,user_info)
                                exit_flag = True
                            elif choice_shopping == 'b':
                                flag1 = True

                else:
                    break
        flag1 = False

def closing(shopping_car,user_info):
    #结账
    total = 0
    print('您的购物车:')
    for i in shopping_car:
        print(i[0],i[1])
        total += i[1]
    print('总计:',total,'')
    transaction.pay(user_info,total)

 

shoppingmanger.py

import os
import sys
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
import json


def shopping_add(shoppinglist):
    #添加商品(未完成)
    with open('shoppinglist.json','w') as f:
        json.dump(shoppinglist,f)

def show_shopping():
    #获取商品列表
    with open('%s\shoppinglist.json' %BASE_DIR,'r') as f:
        data = json.load(f)
        return data

 

总结:

1。代码可复用性太低

2。函数的解释没有实际价值

3。代码重复过多,有些内容差不多是重复的,可以写给一个模块,然后重复调用该模块,根据给的参数给出不同结果就行

4。还是学的不够啊,掌握的不够

 

posted @ 2021-06-21 11:58  二一添作五魁首  阅读(54)  评论(0)    收藏  举报