ATM+购物车

本次代码的实现用到了模块间的互相调用,这对于初学者而言有些难度,不过这也是我们必须要掌握的,在以后的大程序中,多个模块会让我们的代码看起来简洁明了,易排错 (本次代码只是简单的实现的基本的功能,其代码还不是很完美,望各位大神多多指导

对于一个程序而言,读者想要大概了解你的代码都实现了什么功能,READEME是最直接的。这也是我们呈现给读者的窗口。就本次程序而言

├── README
├── ATM #ATM主程目录
│   ├── __init__.py
│   ├── bin #ATM 执行文件 目录
│   │   ├── __init__.py
│   │   ├── atm.py  #ATM 执行程序
│   │  
│   ├── conf #配置文件
│   │   ├── __init__.py
│   │   └── settings.py
│   ├── core #主要程序逻辑都 在这个目录 里
│   │   ├── __init__.py
│   │   ├── accounts.py  #用于从文件里加载和存储账户数据
│   │   ├── auth.py      #用户认证模块及主要功能函数
│   │   ├── db_handler.py   #数据库连接引擎
│   │   ├── logger.py       #日志记录模块
│   │   ├── main.py         #主逻辑交互程序
│   │  
│   ├── db  #用户数据存储的地方
│   │   ├── __init__.py
│   │   ├── account_sample.py #生成一个初始的账户数据 ,把这个数据 存成一个 以这个账户id为文件名的文件,放在accounts目录 就行了,程序自己去会这里找
│   │   └── accounts #存各个用户的账户数据 ,一个用户一个文件
│   │       └── 1234.json #一个用户账户示例文件
│   └── log #日志目录
│       ├── __init__.py
│       ├── access.log #用户访问和操作的相关日志
│       └── login_in.log    #登陆日志
└── shopping_mall #电子商城程序,需单独实现,主要实现购物的功能。
    └── __init__.py

下面是各个模块的源码及主要实现的功能

import os
import sys
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.append(base_dir)

from core import main

if __name__ == "__main__":
    main.run()

atm.py

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

DATABASE = {
    ‘engine‘: ‘file_storage‘,
    ‘name‘: ‘accounts‘,
    ‘path‘: ‘%s\db‘ % BASE_DIR
}

LOG_LIVEL = logging.DEBUG

LOG_TYPES = {
    ‘access‘: ‘access.log‘,
    ‘login_in‘: ‘login_in.log‘
}
TRANSACTION_TYPE = {
    ‘repay‘:{‘action‘:‘plus‘, ‘interest‘:0},
    ‘withdraw‘:{‘action‘:‘minus‘, ‘interest‘:0.05},
    ‘transfer‘:{‘action‘:‘minus‘, ‘interest‘:0.05},
    ‘consume‘:{‘action‘:‘minus‘, ‘interest‘:0},

}

settings.py

from core import db_handler
from conf import settings
import json

def account_load(user_id):

    db_path = db_handler.db_handler(settings.DATABASE)
    new_user_file = "%s\%s.json" % (db_path, user_id)
    with open(new_user_file, "r") as f:
        user_data = json.load(f)
        return user_data

def account_dump(new_accounts):
    db_path = db_handler.db_handler(settings.DATABASE)
    new_user_file = "%s\%s.json" % (db_path, new_accounts[‘id‘])
    with open(new_user_file, "w") as f:
        json.dump(new_accounts, f)
    return True

account.py

import json
import re
from core import db_handler
from conf import settings
from core import account
from core import logger
import logging

tran_logger = logger.logger(‘access‘)

def make_transaction(tran_logger,user_data,tran_type,amount_money):
    amount_money = float(amount_money)
    if tran_type in settings.TRANSACTION_TYPE:
        intertest = amount_money * settings.TRANSACTION_TYPE[tran_type][‘interest‘] # 算的利息
        old_money = user_data[‘balance‘]
        if settings.TRANSACTION_TYPE[tran_type][‘action‘] == "plus":
            new_balance = old_money + amount_money + intertest
        elif settings.TRANSACTION_TYPE[tran_type][‘action‘] == "minus":
            new_balance = old_money - amount_money - intertest
            if new_balance < 0:
                print("余额不足")
                return
        user_data[‘balance‘] = new_balance
        new_balance = user_data
        account.account_dump(new_balance)
        tran_logger.debug("this trans is success and you remain %s money" % (new_balance[‘balance‘]))

        return new_balance
    else:
        print("输入有误")

def withdraw(user_data):
    user_data = account.account_load(user_data[‘id‘])
    print("信用卡现有金额 %s" % (user_data[‘balance‘]))

    flag = False
    while not flag:
        withdraw_money = input("输入你想要取的金额>>>>").strip()
        if len(withdraw_money) > 0 and withdraw_money.isdigit():
            new_user_data = make_transaction(tran_logger, user_data, ‘withdraw‘, withdraw_money)
            if new_user_data:
                print("还剩余额%s" % (new_user_data[‘balance‘]))
                # tran_logger.debug("this trans is success and you tack %s money" %(withdraw_money) )
            flag = True

def repay(user_data):
    user_data = account.account_load(user_data[‘id‘])
    print("信用卡现有金额 %s" % (user_data[‘balance‘]))
    flag = False
    while not flag:
        repay_money = input("输入你要存取的金额>>>>").strip()
        if len(repay_money) > 0 and repay_money.isdigit():
            new_user_data = make_transaction(tran_logger, user_data, ‘repay‘, repay_money)
            if new_user_data:
                print("信用卡金额%s" % (new_user_data[‘balance‘]))
                # tran_logger.debug("this trans is success and you save %s money" % (repay_money))
            flag = True
def transfer(user_data):
    user_data = account.account_load(user_data[‘id‘])
    print("信用卡金额%s" % (user_data[‘balance‘]))
    flag = False
    while not flag:
        tran_id = input("请输入对方信用卡ID>>>>>").strip()
        tran_money = input("请输入要转的金额>>>>").strip()
        if tran_id.isdigit():
            if len(tran_money) > 0 and tran_money.isdigit():
                new_user_data = make_transaction(tran_logger,user_data, ‘transfer‘, tran_money)
                if new_user_data:
                    print("信用卡剩余金额%s" % (new_user_data[‘balance‘]))
                    # tran_logger.debug("this trans is success and you transfer %s money to %s" % (tran_money,tran_id))
                flag = True

def spend():
    db_path = settings.BASE_DIR
    new_user_file = "%s\log\\access.log" % (db_path)
    # with open(new_user_file, "r") as f:
    #     user_data = json.load(f)
    #     print(user_data)
    f = open(new_user_file,‘r‘)
    a = f.read()
    # i = re.compile(‘20\d{2}-\d+-\d+‘)
    # data = i.findall(a)

    print(a)
    f.close()
def xiaofei(shop_price,counts):
    flag = False
    while not flag:
        xiaofei_money = shop_price

        db_path = db_handler.db_handler(settings.DATABASE)
        new_user_file = "%s/%s.json" % (db_path, counts)
        # print(new_user_file,"+++++++++++++")
        with open(new_user_file,"r") as f:
            user_data = json.load(f)
            if user_data[‘balance‘] < shop_price:
                print("余额不足")
            else:
                new_balance = float(user_data[‘balance‘]) - float(xiaofei_money)
                user_data[‘balance‘] = new_balance
                new_user_data = user_data

                with open(new_user_file, "w") as f:
                    json.dump(new_user_data, f)
                    print("信用卡中剩余金额", new_user_data[‘balance‘])
                    tran_logger.debug("this trans is success and you spend %s money" % (xiaofei_money))
        flag = True

auth.py

def db_path(user_date):

    user_path = "%s\%s" % (user_date[‘path‘], user_date[‘name‘])#user_data 相当于 settings.DATABASE
    return user_path

def db_handler(user_data):
    if user_data[‘engine‘] == "file_storage":
        return db_path(user_data)

db_handle.py

import logging
from conf import settings

def logger(log_type):

    logger = logging.getLogger(log_type)
    logger.setLevel(settings.LOG_LIVEL)#设置等级

    ch = logging.StreamHandler() #屏幕对象
    ch.setLevel(settings.LOG_LIVEL)

    log_file = "%s\log\%s" % (settings.BASE_DIR, settings.LOG_TYPES[log_type])

    fh = logging.FileHandler(log_file)#文件对象
    fh.setLevel(settings.LOG_LIVEL)

    #日志输出格式
    formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)

    ch.setFormatter(formatter)
    fh.setFormatter(formatter)

    logger.addHandler(ch)
    logger.addHandler(fh)

    return logger

logger.py

import os
import json
import logging
from core import db_handler
from conf import settings
from core import logger
from core import auth

user_logger = logger.logger(‘login_in‘)

None_user_data = {
        ‘user_id‘: None,
        ‘user_data‘: None,
        ‘is_auth‘: False
}

def show_user(user_data):
    print(user_data)
def drow_money(user_data):
    auth.withdraw(user_data)
def repay_money(user_data):
    auth.repay(user_data)
def tran_money(user_data):
    auth.transfer(user_data)
def spend_bill(user_data):
    auth.spend()
def logout(user_data):
    print("欢迎下次光临")
    exit()

def user_menu(user_data):
    print("欢迎来到信用卡操作系统".center(50, "-"))
    menu = ‘‘‘
        1:显示用户信息
        2:取款
        3:存款
        4:转账
        5:打印账单
        6:退出

    ‘‘‘
    menu_dic = {
        "1": show_user,
        "2": drow_money,
        "3": repay_money,
        "4": tran_money,
        "5": spend_bill,
        "6": logout
    }
    print(menu)
    flag = False
    while not flag:
        choice = input("请输入要操作的项>>>").strip()
        if choice in menu:
            menu_dic[choice](user_data)
        else:
            print("no exit")

def login_auth(accounts, password):
    db_path = db_handler.db_handler(settings.DATABASE)  # D:\python代码\ATM/db/accounts
    # print(db_path)
    user_file = "%s\%s.json" % (db_path, accounts)  # D:\python代码\ATM/db/accounts/1234
    # print(user_file, "111111111")

    if os.path.isfile(user_file):
        # print("---------------------")
        with open(user_file, "r") as f:
            accounts_data = json.load(f)  # 打开db里的用户信息
            # print(accounts_data[‘password‘],type(accounts_data[‘password‘]),"+++++++++++++++++")
            if accounts_data[‘password‘] == password:
                # print("aaaaaaaaaaaaaaaaaaaaaa")

                return accounts_data
            else:
                print("error")
    else:
        print("no exit!!!")
def login(None_user_data,log_obj):
    count = 0

    while None_user_data[‘is_auth‘] is not True and count < 3:
        accounts = input("输入用户名>>>").strip()
        password = input("输入密码>>>").strip()
        new_user = login_auth(accounts, password)
        # print(new_user,"....................")
        if new_user:
            None_user_data[‘is_auth‘] = True
            None_user_data[‘user_id‘] = accounts
            return new_user
        count += 1
    else:
        log_obj.debug("Please check the account number or password")
        exit()

def run():
    #验证用户名id和密码
    user_data = login(None_user_data,user_logger)
    print(user_data)
    # print(None_user_data)
    if None_user_data[‘is_auth‘]:
        None_user_data[‘user_data‘] = user_data
        # print(None_user_data)
        user_menu(user_data)

main.py

import json
acc_dic = {
    ‘id‘: 1234,
    ‘password‘: ‘abc‘,
    ‘credit‘: 15000,
    ‘balance‘: 30000,
    ‘enroll_date‘: ‘2016-01-02‘,
    ‘expire_date‘: ‘2021-01-01‘,
    ‘pay_day‘: 22,
    ‘status‘: 0
}

# print(json.dumps(acc_dic))
with open("1234.json","w") as f:
    json.dump(acc_dic,f)

account_sample.py

import os
import sys
import json
#
base_dir = os.path.dirname(os.path.dirname(__file__))
# print(base_dir)
# sys.path.append(base_dir)
db_path = "%s/ATM主目录" % (base_dir)
sys.path.append(db_path)
from core import db_handler
from conf import settings
from db import account_sample
from core import auth
user_data_file = "%s/accounts" %(db_path)

shop_file = "%s/shpping_mall/shop1.json" % (base_dir)
shop_list = []
# shop_car = {}
if os.path.isfile(shop_file):
    with open(shop_file, "r") as f:
        shop1 = json.load(f)
        shop_car = {}
        for i in shop1:
            print(i[‘name‘], i[‘price‘])
        # print(shop1)
        counts = input("输入你的信用卡ID")
        while True:

            shop_choice = input("请输入你想购买的商品,退出结算请按 q/Q>>>>>")
            if shop_choice.lower() == "q":
                break

            for item in shop1:

                if item[‘name‘] == shop_choice:
                    name = item[‘name‘]

                    if name in shop_car.keys():
                       shop_car[name][‘num‘] += 1
                    else:
                        shop_car[name] = {‘num‘: 1, ‘price‘: item[‘price‘]}

        print("您购买的商品%s" % (shop_car))
        all_money = 0

        for k, v in shop_car.items():
            n = v[‘price‘]
            m = v[‘num‘]
            money = n * m

            all_money = all_money + money
        print(all_money)
        auth.xiaofei(all_money,counts)

else:
    print("no shop_file!!!")

go_shopping.py

下面是执行过程中打印的日志信息

2016-09-23 23:19:43,010 - access - DEBUG - this trans is success and you remain 439994.2000000001 money
2016-09-23 23:19:48,881 - access - DEBUG - this trans is success and you remain 429494.2000000001 money
2016-09-23 23:20:00,706 - access - DEBUG - this trans is success and you remain 429694.2000000001 money
2016-09-23 23:20:16,022 - access - DEBUG - this trans is success and you remain 430260.2000000001 money
2016-09-23 23:20:34,724 - access - DEBUG - this trans is success and you remain 429992.416570.150004500000001 money
2016-09-23 23:20:49,748 - access - DEBUG - this trans is success and you remain 416840.15000000014 money
2016-09-23 23:23:41,075 - access - DEBUG - this trans is success and you spend 60 money
2016-09-23 23:25:34,224 - access - DEBUG - this trans is success and you remain 000014 money
2016-09-27 12:27:03,227 - access - DEBUG - this trans is success and you remain 416360.15000000014 money
2016-09-27 12:28:05,456 - access - DEBUG - this trans is success and you remain 416150.15000000014 money
2016-09-27 12:28:53,546 - access - DEBUG - this trans is success and you remain 415940.15000000014 money
2016-09-23 22:56:38,035 - login_in - DEBUG - Please check the account number or password

  

 

时间: 2024-12-29 23:29:48

ATM+购物车的相关文章

Python实战之ATM+购物车

ATM + 购物车 需求分析 ''' - 额度 15000或自定义 - 实现购物商城,买东西加入 购物车,调用信用卡接口结账 - 可以提现,手续费5% - 支持多账户登录 - 支持账户间转账 - 记录每月日常消费流水 - 提供还款接口 - ATM记录操作日志 - 提供管理接口,包括添加账户.用户额度,冻结账户等... - 用户认证功能 ''' 一个项目是如何从无到有的 # 1.需求分析: ''' 开发项目前,都必须找到相应的客户,让客户给企业提出项目的需求,以及需要实现的功能有哪些,拿到需求后再

ATM+购物车完整版

代码视频之一:https://www.bilibili.com/video/BV1Cc411h78m/ 更多ATM代码视频请浏览:https://space.bilibili.com/516735973 一 项目三层结构设计 在项目开发中,清晰明了的结构设计非常重要.它的重要性至少提现在三个方面:结构清晰:可维护性强:可扩展性高. 常用的项目结构设计中,三层架构设计非常实用.这种架构设计模式将整个程序分为三层: 用户视图层:用于与用户交互的,可以接受用户的输入,打印接口返回的数据. 逻辑接口层:

ATM购物车部分功能

额度 15000或自定义 实现购物商城,买东西加入 购物车,调用信用卡接口结账 可以提现,手续费5% 每月22号出账单,每月10号为还款日,过期未还,按欠款总额 万分之5 每日计息 支持多账户登录 支持账户间转账 记录每月日常消费流水 提供还款接口 ATM记录操作日志 提供管理接口,包括添加账户.用户额度,冻结账户等... 用户认证用装饰器 思维导图 目录结构 atm作业 ├── README ├── atm #ATM主程目录 │ ├── bin #ATM 执行文件 目录 │ │ ├── __i

python ATM + 购物车

一.项目介绍 ATM + 购物商城程序其实是通过模拟银行ATM机功能以及电商平台<购物商城程序>功能的实现,将前面大部分所学的知识点串联起来, 更好的去巩固python基础.这也是在学习python这门语言的第一个程序. 项目需求如下: - 额度 15000或自定义 - 实现购物商城,买东西加入 购物车,调用信用卡接口结账 - 可以提现,手续费5% - 支持多账户登录 - 支持账户间转账 - 记录每月日常消费流水 - 提供还款接口 - ATM记录操作日志 - 提供管理接口,包括添加账户.用户额

ATM+购物车(部分代码——三层框架)

启动文件 run.py from core import src if __name__ == '__main__': src.main() 用户视图层 src.py # 用户视图层 from interface import user_interface from interface import bank_interface from interface import shopping_interface from lib import common # 记录用户登录状态 login_use

ATM程序项目规范

ATM购物车程序(练习) ------------README 作者:飞乐 版本:示例版本 v0.1 程序介绍: 实现ATM常用功能 功能全部用python的基础知识实现,用到了time\os\sys\open\函数\模块知识, 主要帮给大家一个简单的模块化编程的示例 注意:只实现了"认证","注册","购物"和"支付"功能 程序结构: ATM--/ ├——─ README ├── atm #ATM主程目录 │   ├── _

【新项目】ATM机+商场系统逻辑

新项目,上逻辑 #!/usr/bin/env python # -*- coding: utf-8 -*- '''''' #做项目 ''' 1.调研 2.需求分析 3.任务分配 4.写项目demo(架构师) 5.架构分析 6.编写代码 7.测试 8.上线(产品) ''' ''' ATM + 购物车思路构想 一.需要实现的功能 项目需求: --购物商场需求 1.用户信息由文件存放 2.实现 登录,注册,注销,购物,充值,退出系统 六个功能 3.注册可以完成用户的注册,注册时要提供账号密码,初始财产

python 23 ATM

1,分析需求 1.额度15000或自定义 --> 注册功能 2.实现购物商城,买东西加入购物车,调用信用卡接口结账 --> 购物功能.支付功能 3.可以提现,手续费5% --> 提现功能 4.支持多账户登录 --> 登录功能 5.支持账户间转账 --> 转账功能 6.记录日常消费 --> 记录流水功能 7.提供还款接口 --> 还款功能 8.ATM记录操作日志 --> 记录日志功能 9.提供管理接口,包括添加账户.用户额度,冻结账户等... --->

26、ATM项目的编写流程

1.搭建项目的目录规范 - ATM 项目根目录 - readme.md 项目的说明书 - start.py 项目启动文件 - conf 配置文件 - settings.py - lib 公共方法文件 - common.py - core(用户视图层) 存放用户视图层代码文件 - src.py - interface(逻辑接口层) 存放核心业务逻辑代码 - user_interface.py 用户相关的接口 - bank_interface.py 银行相关的接口 - shop_interface.