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

对于一个程序而言,读者想要大概了解你的代码都实现了什么功能,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 = {
"": show_user,
"": drow_money,
"": repay_money,
"": tran_money,
"": spend_bill,
"": 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

  

 

ATM+购物车的更多相关文章

  1. day19 十九、ATM+购物车

    项目:ATM+购物车 作业需求:模拟实现一个ATM + 购物商城程序1.额度 15000或自定义 2.实现购物商城,买东西加入 购物车,调用信用卡接口结账 3.可以提现,手续费5% 4.每月22号出账 ...

  2. Python 入门基础16 -- ATM + 购物车

    ATM + 购物车 1.需求分析 2.设计程序以及程序的架构 设计程序的好处: - 扩展性强 - 逻辑清晰 3.分任务开发 4.测试 黑盒: 白盒: 对程序性能的测试 5.上线运行 # Tank -- ...

  3. ATM购物车程序项目规范(更新到高级版)

    ATM购物车程序(高级版) 之前的低级版本已经删除,现在的内容太多,没时间把内容上传,有时间我会把项目源码奉上! 我已经把整个项目源码传到群文件里了,需要的可以加主页qq群号.同时群内也有免费的学习资 ...

  4. python以ATM+购物车剖析一个项目的由来及流程

    ATM+购物车 一个项目是如何从无到有的 ''' 项目的由来,几个阶段 0.采集项目需求 1.需求分析 2.程序的架构设计 3.分任务开发 4.测试 5.上线运行 ''' 需求分析: # 对项目需求进 ...

  5. Python实战之ATM+购物车

    ATM + 购物车 需求分析 ''' - 额度 15000或自定义 - 实现购物商城,买东西加入 购物车,调用信用卡接口结账 - 可以提现,手续费5% - 支持多账户登录 - 支持账户间转账 - 记录 ...

  6. 阶段性项目 ATM+购物车项目

    ATM + 购物车https://www.cnblogs.com/kermitjam/articles/10687180.html readme 内容前戏: 一个项目是如何从无到有的. 一 需求分析 ...

  7. ATM+购物车结构

    ATM+购物车 1.需求分析 2.程序设计及目录设计 3.编写程序 4.调试程序

  8. ATM购物车+三层结构项目设计

    ATM购物车项目 模拟实现一个ATM + 购物商城程序. 该程序实现普通用户的登录注册.提现充值还款等功能,并且支持到网上商城购物的功能. 账户余额足够支付商品价格时,扣款支付:余额不足时,无法支付, ...

  9. ATM + 购物车项目

    ''' 存放配置文件 ''' import os #获取项目根目录 BASE_PATH=os.path.dirname(os.path.dirname(__file__)) #获取用户目录 USER_ ...

  10. 项目: ATM+购物车

    ATM+购物车 项目文件: 介绍 以下为文件夹层次和内容: readme.md 1. 需求 模拟银行取款 + 购物全过程 1.注册 2.登录 3.提现 4.还款 5.转账 6.查看余额 7.查看购物车 ...

随机推荐

  1. [bigdata] flume file channel CPU消耗比 memory channel高的原因

    https://www.quora.com/Why-does-flume-take-more-resource-CPU-when-file-channel-is-used-compared-to-wh ...

  2. LINQ函数

    LINQ函数虽然和LINQ语句实现了同样的功能,但LINQ函数使用起来更加快捷.学过数据库的感觉LINQ语句都不难,但语句比较长. 会LINQ函数,才算会LINQ. 1.Where(),结果过滤 Li ...

  3. 让 FreeBSD 和 Gentoo Linux 在 ZFS 存储卷上共存

    自我回归到 Librem 15 已经有段时间了.我一般会选择 FreeBSD 来处理所有的事情,但有时会要访问一个运行在 Librem 平台上的 Linux OS,以便用它来帮助我对一些遗留的设备驱动 ...

  4. 【JavaWeb】SSM+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(六)

    Showings 我个人的项目,当前不断地在更新. 我希望做成一个好项目,同时,也是在锻炼自己的技术. 在项目中发现问题,学习知识,是比较可取的一条路子. 这样学习到的知识,虽然分散,但是都很实用,而 ...

  5. maven 加入json-lib.jar 报错 Missing artifact net.sf.json-lib:json-lib:jar:2.4:compile

    <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</art ...

  6. 谷歌浏览器,火狐浏览器,ie浏览器解析顺序

    谷歌(版本 55.0.2883.87 m),火狐(48.0.2),ie(11.576.14393.0)对三个浏览器简单的进行了一下试验发现,谷歌浏览器是等到html全部解析完毕之后才开始渲染,而另外两 ...

  7. GNU Radio Radar Toolbox

    GNU Radio Radar Toolbox Install guide Change to any folder in your home directory and enter followin ...

  8. [Bash Shell] Shell学习笔记

    1. Shell简介 Shell本身是一个用C语言编写的程序,它是用户使用Unix/Linux的桥梁,用户的大部分工作都是通过Shell完成的.Shell既是一种命令语言,又是一种程序设计语言.作为命 ...

  9. 关于形变属CGAffineTransform性介绍

    CGAffineTransformMakeTranslation每次都是以最初位置的中心点为起始参照 CGAffineTransformTranslate每次都是以传入的transform为起始参照, ...

  10. Maven模块聚合

    一个Maven工程中一般会有很多模块组成,为了构建的方便通常想一次构建多个模块,Maven聚合这一特性就是为该需求服务的. 假设我们有account-email和account-persist两个模块 ...