付出模块,python开发简单ATM加购物车

By admin in 4858.com on 2019年2月10日
模拟实现一个ATM + 购物商城程序
    1.额度 15000或自定义                                        
    4.支持多账户登录                                            
    5.支持账户间转账                                           
    9.提供管理接口,包括添加账户、用户额度,冻结账户等。。。          
    10.用户认证用装饰器                                          
    3.可以提现,手续费5%                                        
    2.实现购物商城,买东西加入 购物车,调用信用卡接口结账            
    6.记录每月日常消费流水                                       
    7.提供还款接口                                              
    8.ATM记录操作日志                                           
    包含随时返回:b   和随时退出:q

ps:使用面向过程的思想去实现

作者:Vamei
出处:http://www.cnblogs.com/vamei
欢迎转发,也请保留那段申明。多谢!
安装阿里云的python镜像地址:
# vim ~/.pip/pip.conf
# [global]
# trusted-host=mirrors.aliyun.com
#
index-url=http://mirrors.aliyun.com/pypi/simple/
安装django:(会自动uninstall 之前的django版本)
# sudo pip install django==1.8
阿里云,速度杠杠滴,感激阿里云。
检查django的版本:
# import django
# print (django.VERSION)
启动django:
# django-admin.py startproject mysite 在当前目录成立django项目目录
# ├── manage.py
# └── mysite
# ├── init.py
# ├── settings.py
# ├── urls.py
# └── wsgi.py
# python3.4 manag.py runserver 0.0.0.0:8000
测试django默许网页:
# curl
django第四个网页:
# vim mysite/urls.py
# from django.conf.urls import patterns, include, url
# from django.contrib import admin
# admin.autodiscover()
# urlpatterns = patterns (”,
# url(r’^admin/’, admin.site.urls),
# url(r’^$’,’mysite.views.first_page’)
# )
# 将根目录请求提交mysite.views.first_page那一个目的处理。
# vim mysite/views.py
# # –– coding: utf-8 –
# from django.http import HttpResponse
# def first_page(request):
# return HttpResponse(“<p> Hello ,world!</p>”)
#付出模块,python开发简单ATM加购物车。 first_page这几个目标对请求return一个httpresponse对象。(hello,world!)
增加APP:
mysite目录下增添westAPP程序
# python3.4 manage.py startapp west
# neo@neo-virtual-machine:~/python3/mysite$ tree
# ├── manage.py
# ├── mysite
# │ ├── init.py
# │ ├── pycache
# │ ├── settings.py
# │ ├── urls.py
# │ ├── views.py
# │ └── wsgi.py
# └── west
# ├── admin.py
# ├── init.py
# ├── migrations
# │ └── init.py
# ├── models.py
# ├── tests.py
# └── views.py
在mysite/settings.py添加设置west项目
# vim mysite/settings.py
# INSTALLED_APPS = [
# ‘django.contrib.admin’, //管理
# ‘django.contrib.auth’, //用户认证
# ‘django.contrib.contenttypes’, //内容类型
# ‘django.contrib.sessions’, //会话管理
# ‘django.contrib.messages’, //消息
# ‘django.contrib.staticfiles’, //静态文件
# ‘west’, //自定义app
# ]
增加APP页面:
# 在mysite/urls.py配置文件的urlpatterns元组对象中添加
# url(r’^west/’,include(‘west.urls’)),
# 接着在west目录下开创urls.py文件
# vim west/urls.py
# # –– coding: utf-8 –
# from django.conf.urls import patterns, include, url
#4858.com , urlpatterns = patterns (”,
# url(r’^$’,’west.views.first_page’),
# )
# 在west目录下修改views.py的页面文件
# # –– coding: utf-8 –
# from django.shortcuts import render
# from django.http import HttpResponse
# # Create your views here.
# def first_page(request):
# return HttpResponse(“<p>世界,你好.</p>”)
做客测试:
# neo@neo-virtual-machine:~/python3/mysite$ curl
http://127.0.0.1:8000/west/
# <p>世界,你好.</p>
django报错:
ImportError: cannot import name ‘patterns’
新本子的django没有此措施,在django1.8版本存在。
疑问:
1、在新本子1.10(近期python3.4的djangp阿里云新版本应该是1.10),如何落实简单页面?
2、ubuntu系统时间展现正确,在python启动django是,日志时间展现不科学?
[20/Feb/2017 01:28:06]”GET /west/ HTTP/1.1″ 200 23
[20/Feb/2017 01:28:08]”GET /west/ HTTP/1.1″ 200 23
3、后台运行:
python3.4 manage.py runserver 0.0.0.0:8000 &

在开发模块以前,现问下团结多少个难点?

  1. 官方是不是有提供的切近成效模块?
    可从底下多个接二连三确定官方提供的模块,防止再一次造轮子
    官方已发布的模块
    http://docs.ansible.com/ansible/modules.html
    法定正在开发的模块
    https://github.com/ansible/ansible/labels/module
  2. 你必要开销一个action 插件么?
    action插件是在ansible主机上运行,而不是在对象主机上运行的。对于接近file/copy/template功能的模块,在模块执行前须要在ansible主机上做一些操作的。有关action插件的成本请移步到

2-5 互连网互连和套接字

先运行服务器,然后启动客户端,客户端可输入任意指令,若输入了dateosls之一,则会相应从服务器重回时间戳、当前操作系统音信,当前目录文件清单

4858.com 1

4858.com 2

明朗几点

- 模块是传送到目标主机上运行的。
- 模块的返回值必须是json dumps的字符串。

echoserv.py

# coding=utf-8
# TCP服务器程序
import socket
from time import ctime
import os
HOST = ''
PORT = 50007

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST,PORT))
    s.listen(1)
    conn, addr = s.accept()
    msg = b''
    with conn:
        print('Connected by',addr)
        while True:
            data = conn.recv(1024)
            if not data:break
            print('Received ',data)
            if data == b'date':
                msg = bytes('[%s]' % ctime(), 'utf-8')
            elif data == b'os':
                msg = bytes('[%s]' % os.name,'utf-8')
            elif data == b'ls':
                msg = bytes('[%s]' % os.listdir(),'utf-8')
            else:
                msg = data
            conn.sendall(msg)
画的贼烂,框架如上图

ATM+购物车
    |-------conf 配置加接口
    |        |------interface.py  接口配置
    |        |------settings.py   路径加日志配置
    |
    |-------core 核心  用户与超管
    |        |------admin.py  超管功能
    |        |------atm.py    ATM功能
    |        |------shopping.py  购物功能
    |
    |-------db  数据库
    |        |------userdb  用户文件 json格式
    |        |------dbhandler.py  数据层操作
    |
    |-------lib  公共库
    |        |------common.py  用户认证加日志功能
    |
    |-------log 日志文件夹
    |        |------operation.log  操作日志
    |        |------trading.log    交易日志
    |-------start.py  程序启动文件

进行模块的长河

4858.com 3

image.png

首先,将模块文件读入内存,然后添加传递给模块的参数,最后将模块中所要求的类添加到内存,由zipfile压缩后,再由base64举行编码,写入到模版文件内。

经过默许的连年形式,一般是ssh。ansible通过ssh连接到远程主机,创立临时目录,并关闭连接。然后将开辟其余一个ssh连接,将模版文件以sftp格局传送到刚刚创建的暂时目录中,写完后关闭连接。然后打开一个ssh连接将任务目标给予可举办权限,执行成功后关闭连接。

说到底,ansible将开辟第多少个延续来执行模块,并剔除临时目录及其所有剧情。模块的结果是从标准输出stdout中赢得json格式的字符串。ansible将分析和拍卖此字符串。如若有职分是异步控制执行的,ansible将在模块形成此前关闭第多个两次三番,并且重返主机后,在确定的日子内检查任务情况,直到模块形成或确定的时光超时。

使用了管道连接后,与远程主机只有一个连续,命令通过数据流的办法发送执行。

布局格局

vim /etc/ansible/ansible.cfg
pipelining = True

推行进度

4858.com 4

image.png

echoclnt.py

# coding=utf-8
# TCP客户端程序
import socket
HOST = 'localhost'
PORT = 50007

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST,PORT))
    data=input('> ')
    s.sendall(bytes(data,'utf-8'))
    data = s.recv(1024)
print('Received',data.decode('utf-8'))

 

模块工具


Ansible提供了过多模块实用程序,它们提供了在开发协调的模块时能够行使的扶助功用。
basic.py模块为顺序提供访问Ansible库的机要入口点,所有Ansible模块必须至少从basic.py导入:
from ansible.module_utils.basic import *

任何模块工具
a10.py – Utilities used by the a10_server module to manage A10 Networks
devices.
api.py – Adds shared support for generic API modules.
aos.py – Module support utilities for managing Apstra AOS Server.
asa.py – Module support utilities for managing Cisco ASA network
devices.
azure_rm_common.py – Definitions and utilities for Microsoft Azure
Resource Manager template deployments.
basic.py – General definitions and helper utilities for Ansible
modules.
cloudstack.py – Utilities for CloudStack modules.
database.py – Miscellaneous helper functions for PostGRES and MySQL
docker_common.py – Definitions and helper utilities for modules working
with Docker.
ec2.py – Definitions and utilities for modules working with Amazon EC2
eos.py – Helper functions for modules working with EOS networking
devices.
f5.py – Helper functions for modules working with F5 networking
devices.
facts.py – Helper functions for modules that return facts.
gce.py – Definitions and helper functions for modules that work with
Google Compute Engine resources.
ios.py – Definitions and helper functions for modules that manage Cisco
IOS networking devices
iosxr.py – Definitions and helper functions for modules that manage
Cisco IOS-XR networking devices
ismount.py – Contains single helper function that fixes
os.path.ismount
junos.py – Definitions and helper functions for modules that manage
Junos networking devices
known_hosts.py – utilities for working with known_hosts file
mysql.py – Allows modules to connect to a MySQL instance
netapp.py – Functions and utilities for modules that work with the
NetApp storage platforms.
netcfg.py – Configuration utility functions for use by networking
modules
netcmd.py – Defines commands and comparison operators for use in
networking modules
network.py – Functions for running commands on networking devices
nxos.py – Contains definitions and helper functions specific to Cisco
NXOS networking devices
openstack.py – Utilities for modules that work with Openstack
instances.
openswitch.py – Definitions and helper functions for modules that manage
OpenSwitch devices
powershell.ps1 – Utilities for working with Microsoft Windows clients
pycompat24.py – Exception workaround for Python 2.4.
rax.py – Definitions and helper functions for modules that work with
Rackspace resources.
redhat.py – Functions for modules that manage Red Hat Network
registration and subscriptions
service.py – Contains utilities to enable modules to work with Linux
services (placeholder, not in use).
shell.py – Functions to allow modules to create shells and work with
shell commands
six/init.py – Bundled copy of the Six Python library to aid in
writing code compatible with both Python 2 and Python 3.
splitter.py – String splitting and manipulation utilities for working
with Jinja2 templates
urls.py – Utilities for working with http and https requests
vca.py – Contains utilities for modules that work with VMware vCloud
Air
vmware.py – Contains utilities for modules that work with VMware vSphere
VMs
vyos.py – Definitions and functions for working with VyOS networking

2-6 Daytime服务

赢得端口号应该是13
getservbyname("daytime","udp")

4858.com 54858.com 6

udpserv.py

# coding=utf-8
# UDP服务器程序
from socket import *
from time import ctime

HOST = ''
# 确定使用UDP协议的“daytime”服务的端口号
PORT=getservbyname("daytime","udp")
print('使用UDP协议的“daytime”服务的端口号为%s' % PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)

# udpSerSock = socket(AF_INET, SOCK_STREAM)
udpSerSock = socket(AF_INET, SOCK_DGRAM)
udpSerSock.bind(ADDR)

try:
    while True:
        print('waiting for message...')
        data, addr = udpSerSock.recvfrom(BUFSIZ)
        if not data:
            break
        udpSerSock.sendto(bytes('[%s] %s' % (ctime(),data.decode('utf-8')),'utf-8'),addr)
        print('...received from and returned to:', addr)
except Exception as err:
    print("[UDP_SERVE_ERROR] " + str(err))
finally:
    udpSerSock.close()
#coding:utf-8
from db import dbhandler
from lib import common

logger1=common.get_logger("操作日志")

logger2=common.get_logger('交易日志')

def add_user(name,pwd='123',lines=15000):
    '''添加账户接口'''
    user_dict={'name':name,'password':pwd,'lines':lines,'balance':lines,'buy':[],'lock':False}
    state,msg=dbhandler.query(name)
    if state:
        return False,'用户已存在'
    else:
        dbhandler.save(user_dict)
        logger1.info('%s用户创建成功' % name)
        return True, '%s用户创建成功,密码为%s' % (name,pwd)

def trans_interface(my_name,trans_name,money):
    '''转账接口'''
    state_my,msg_my=dbhandler.query(my_name)
    state_tra,msg_tra=dbhandler.query(trans_name)
    if state_tra:
        if int(money) < int(msg_my['balance']):
            msg_my['balance']=int(msg_my['balance'])-int(money)
            msg_tra['balance']=int(msg_tra['balance'])+int(money)
            dbhandler.save(msg_my)
            dbhandler.save(msg_tra)
            logger2.info('%s转账给%s%s元成功'%(my_name,trans_name,money))
            return True,'%s转账给%s%s元成功'%(my_name,trans_name,money)
        else:
            return False,'转账失败,余额不足'
    else:
        return False,'转账用户不存在'

def withdrawal_interface(name,money):
    '''提现接口'''
    state,msg=dbhandler.query(name)
    poundage=int(money)*5/100
    if msg['balance'] < (int(money)+poundage):
        return False,'提现失败,余额不足'
    else:
        msg['balance']=msg['balance'] - int(money) - poundage
        dbhandler.save(msg)
        logger2.info('%s提现%s元成功,手续费为%s元'%(name,money,poundage))
        return True,'%s提现%s元成功,手续费为%s元'%(name,money,poundage)

def repay_interface(name,money):
    '''还款接口'''
    state,msg=dbhandler.query(name)
    if state:
        msg['balance']=msg['balance']+int(money)
        dbhandler.save(msg)
        logger2.info('%s还款%s元成功,余额为%s'%(name,money,msg['balance']))
        return True,'%s还款%s元成功,余额为%s'%(name,money,msg['balance'])

def check_balance(name):
    '''查看余额接口'''
    state,user_dict=dbhandler.query(name)
    res=user_dict['balance']
    return res

def shopping_interface(name,cost,shopping_dict):
    '''购物支付接口'''
    state,user_dict=dbhandler.query(name)
    if user_dict['balance'] > cost:
        user_dict['balance']-=cost
        user_dict['buy'].append(shopping_dict)
        dbhandler.save(user_dict)
        logger2.info('%s购买成功,消费了%s元'%(name,cost))
        return True,'购买成功,消费了%s元'%cost
    else:
        return False,'余额不足,购买失败'

def check_shop_car(name):
    '''查看购物记录即可'''
    state,user_dict=dbhandler.query(name)
    res=user_dict['buy']
    return res

udpclnt.py

# coding=utf-8
# UDP客户端
from socket import *

HOST = 'localhost'
# 确定使用UDP协议的“daytime”服务的端口号
PORT=getservbyname("daytime","udp")
print('使用UDP协议的“daytime”服务的端口号为%s' % PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)

udpCliSock = socket(AF_INET,SOCK_DGRAM)
try:
    while True:
        data = input('> ')
        if not data:
            break
        udpCliSock.sendto(bytes(data,'utf-8'),ADDR)
        data,ADDR = udpCliSock.recvfrom(BUFSIZ)
        print(data.decode('utf-8'))
except EOFError as err:
    print("[UDP_CLIENT_ERROR] " + str(err))
finally:
    udpCliSock.close()

interface.py

2-7 半双工聊天

# coding:utf-8
# ============================路径配置加日志配置项(日志配置模板)=========================================
import os

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

USER_DB = os.path.join(BASE_DIR, 'db', 'userdb')

standard_format = '[%(asctime)s][task_id:%(name)s]' \
                  '[%(levelname)s]< %(message)s >'  # 其中name为getlogger指定的名字

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(asctime)s][%(levelname)s] %(message)s'

# log文件的路径
OPE_LOG_PATH = os.path.join(BASE_DIR, 'log', 'operation.log')  # 操作日志路径
TRA_LOG_PATH = os.path.join(BASE_DIR, 'log', 'trading.log')  # 交易日志路径

# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': id_simple_format
        },
    },
    'filters': {},
    'handlers': {
        # 打印到终端的日志,使用的格式为 simple_format
        'ch': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        # 打印到文件的日志,使用的格式为 standard_format
        'default1': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': OPE_LOG_PATH,  # 日志文件
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
        'default2': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': TRA_LOG_PATH,  # 日志文件
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
        '操作日志': {
            'handlers': ['ch', 'default1'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': False,
        },
        '交易日志': {
            'handlers': ['ch', 'default2'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}

tcpserv.py

# coding=utf-8
# TCP半双工聊天服务器程序
from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)


while True:
    tcpCliSock, addr = tcpSerSock.accept()
    while True:
        #接收消息
        data = tcpCliSock.recv(BUFSIZ)
        if not data:
            break
        print('client> ',data.decode('utf-8'))

        #发送消息
        msg = input('server> ')
        tcpCliSock.send(bytes(msg, 'utf-8'))

    tcpCliSock.close()

tcpSerSock.close()

 

tcpclnt.py

# coding=utf-8
# TCP半双工聊天客户端程序
from socket import *

HOST = '127.0.0.1'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    # 发送消息
    data = input('client> ')
    if not data:
        break
    tcpCliSock.send(bytes(data, 'utf-8'))

    # 接收消息
    data = tcpCliSock.recv(BUFSIZ)
    if not data:
        break
    print('server> ',data.decode('utf-8'))

tcpCliSock.close()

4858.com 74858.com 8

效果图

4858.com 9

客户端

4858.com 10

服务端

# coding:utf-8
from conf import interface
from db import dbhandler
from lib import common

tag = True


def adduser():
    '''添加用户'''
    while True:
        name = input('请输入账户名:').strip()
        if not name: continue
        name1 = input('请确认账户名:').strip()
        if name != name1:
            print('两次输入不一致!')
            continue
        state, msg = interface.add_user(name1)
        if state:
            print(msg)
            break
        else:
            print(msg)


def set_lines():
    '''设置额度'''
    while True:
        name = input('请输入账户名:').strip()
        if not name: continue
        name1 = input('请确认账户名:').strip()
        if name != name1:
            print('两次输入不一致!')
            continue
        lines = input('请输入信用额度:').strip()
        if lines.isdigit():
            state, msg = interface.dbhandler.query(name1)
            if state:
                msg['lines'] = lines
                dbhandler.save(msg)
                interface.logger1.info('%s设置%s成功,信用额度为%s!!' % ('admin', name1, lines))
                print('%s设置%s成功,信用额度为%s!!' % ('admin', name1, lines))
            else:
                print(msg)
        else:
            print('额度请输入数字')
            break


def freeze():
    '''冻结功能'''
    name = input('请输入冻结账户名:').strip()
    name1 = input('请确认冻结账户名:').strip()
    if name != name1:
        print('两次输入不一致!')
        return
    state, msg = dbhandler.query(name1)
    if state:
        msg['lock'] = True
        dbhandler.save(msg)
        interface.logger1.info('%s冻结%s成功' % ('admin', name1))
        print('%s冻结%s成功' % (common.user_state['name'], name1))
    else:
        print(msg)


def unfreeze():
    '''解冻功能'''
    name = input('请输入冻结账户名:').strip()
    name1 = input('请确认冻结账户名:').strip()
    if name != name1:
        print('两次输入不一致!')
        return
    state, msg = dbhandler.query(name1)
    if state:
        msg['lock'] = False
        dbhandler.save(msg)
        interface.logger1.info('%s解冻%s成功' % ('admin', name1))
        print('%s解冻%s成功' % ('admin', name1))
    else:
        print(msg)


def check_log():
    '''查看操作日志功能'''
    dbhandler.query_log('admin')


def menu():
    view = '''
        1.添加账户
        2.设置用户额度
        3.冻结账户
        4.解冻账户
        5.查看操作日志
        q.退出
    '''
    print(view)


@common.login_auth(auth='admin')
def main():
    view_dict = {
        '1': adduser,
        '2': set_lines,
        '3': freeze,
        '4': unfreeze,
        '5': check_log
    }
    global tag
    while tag:
        print('管理员'.center(60, '-'))
        menu()
        choice = input('请选择:').strip()
        if choice == 'q':
            tag = False
            break
        if not choice or choice not in view_dict: continue
        view_dict[choice]()

admin.py

4858.com 114858.com 12

# coding:utf-8
from core import admin
from conf import interface
from db import dbhandler
from lib import common


def registered():
    '''注册功能'''
    if common.user_state['name']:
        print('已登录,无法注册')
        return
    while True:
        print('注册'.center(40, '-'))
        name = input('请输入账户名:').strip()
        if not name: continue
        pwd1 = input('请输入密码:').strip()
        if not pwd1: continue
        pwd2 = input('请确认密码:').strip()
        if pwd1 != pwd2:
            print('两次输入密码不一致!')
            break
        if len(pwd2) < 3:
            print('密码强度太低')
            continue
        state, msg = interface.add_user(name, pwd2)
        if state:
            print(msg)
            break
        else:
            print(msg)


def check_balance():
    '''查看余额'''
    balance = interface.check_balance(common.user_state['name'])
    print('%s当前余额为%s元!!!' % (common.user_state['name'], balance))


def transfer():
    '''转账'''
    while True:
        print('转账'.center(40, '-'))
        name = input('请输入要转账的账户名:').strip()
        name1 = input('请确认账户名:').strip()
        if name != name1:
            print('账户名不一致')
            continue
        money = input('请输入转账金额:'.strip())
        if money.isdigit():
            state, msg = interface.trans_interface(common.user_state['name'], name1, money)
            if state:
                print(msg)
                break
            else:
                print(msg)
                break
        else:
            print('金额请输入数字!')
            continue


def repay():
    '''还款'''
    state, msg = dbhandler.query(common.user_state['name'])
    arrears = msg['lines'] - msg['balance']
    print('您的欠款为%s元!!!' % (arrears))
    repay_wage = input('请输入您要还款的金额: ').strip()
    if not repay_wage.isdigit():
        print('请输入数字!')
        return
    else:
        state, msg = interface.repay_interface(common.user_state['name'], repay_wage)
        print(msg)


def withdrawal():
    '''提现'''
    while True:
        print('提现'.center(40, '-'))
        money = input('请输入要提现的金额:').strip()
        if not money.isdigit(): continue
        message = input('提现将要收取%5手续费,是否继续(y/n):').strip()
        if message not in ['y', 'n']: continue
        if message == 'y':
            state, msg = interface.withdrawal_interface(common.user_state['name'], money)
            if state:
                print(msg)
                break
            else:
                print(msg)
        else:
            break


def check_log():
    '''查看操作日志'''
    dbhandler.query_log(common.user_state['name'])


def view():
    view_dict = '''
        1.查询余额
        2.转账
        3.还款
        4.提现
        5.查询日志
        b.返回上一层
        q.退出
    '''
    print(view_dict)


@common.login_auth(auth='user')
def main():
    view_dict = {
        '1': check_balance,
        '2': transfer,
        '3': repay,
        '4': withdrawal,
        '5': check_log
    }
    while admin.tag:
        print('ATM操作界面'.center(60, '-'))
        view()
        choice = input('请选择:').strip()
        if choice == 'q':
            admin.tag = False
            break
        if choice == 'b': break
        if choice not in view_dict: continue
        view_dict[choice]()

atm.py

4858.com 134858.com 14

# coding:utf-8
from lib import common
from core import admin
from conf import interface

shopping_dict = {}  # 购物车

def product():
    '''购物功能'''
    product_list = [
        ['华为P20', 5488],
        ['笔记本', 5599],
        ['Nike运动鞋', 669],
        ['十三香小龙虾', 165],
        ['山地车', 399],
        ['天梭表', 3699],
        ['某宝t恤', 69],
        ['三只松鼠', 59],
        ['重庆小面', 18],
    ]
    cost = 0  # 初始总花费为0
    user_balance = interface.check_balance(common.user_state['name'])  # 调接口查询余额
    global shopping_dict
    while admin.tag:
        print('商品列表'.center(50, '-'))
        for k, v in enumerate(product_list):  # 将商品列表 加上索引打印出来
            print(k, '', v)
        print('q : 退出/购买 ')
        choice = input('\n请选择购买商品:').strip()
        if choice.isdigit():  # 判断输入是否为数字
            choice = int(choice)
            if choice >= len(product_list): continue  # 输入的数字大于索引则重新开始
            product_name = product_list[choice][0]  # 拿到商品名
            product_price = product_list[choice][1]  # 拿到商品价格
            if user_balance >= product_price:  # 判断余额是否大于商品价格
                if product_name in shopping_dict:  # 判断商品是否已在购物车里
                    shopping_dict[product_name]['数量'] += 1  # 有则购物车的对应商品数量加1
                else:
                    shopping_dict[product_name] = {'价格': product_price, '数量': 1}  # 购物车添加新字典
                user_balance -= product_price  # 余额减去商品价格
                cost += product_price  # 花费加上商品价格
                print('%s加入购物车成功' % [product_name, product_price])
            else:
                print('余额不足')
        elif choice == 'q':
            if cost == 0: break
            for k, v in shopping_dict.items():
                print(k, '', v)
            buy = input('是否确认购买(y/n),需支付%s元:' % cost).strip()
            if buy == 'y':  # 确认支付时调支付接口
                state, msg = interface.shopping_interface(common.user_state['name'], cost, shopping_dict)
                if state:
                    print(msg)
                    break
                else:
                    print(msg)
                    break
            else:
                print('无任何商品购买')
                shopping_dict = {}
                break
        else:
            print('输入错误')
            continue


def shop_car():
    '''查看购物车功能'''
    for k, v in shopping_dict.items():
        print(k, '', v)


def check_shop():
    '''查看消费记录功能'''
    shop_dic = interface.check_shop_car(common.user_state['name'])
    for i in shop_dic:
        print(i)


def view():
    view_dict = '''
        1.商品列表
        2.购物车
        3.查看消费记录
        b.返回上一层
        q.退出
    '''
    print(view_dict)


@common.login_auth(auth='user')
def main():
    view_dict = {
        '1': product,
        '2': shop_car,
        '3': check_shop,
    }
    while admin.tag:
        print('购物界面'.center(60, '-'))
        view()
        choice = input('请选择:').strip()
        if choice == 'q':
            admin.tag = False
            break
        if choice == 'b': break
        if choice not in view_dict: continue
        view_dict[choice]()

shopping.py

4858.com 154858.com 16

#coding:utf-8
import json,os
from conf import settings

def save(user_dic):
    '''数据写入'''
    name=user_dic['name']
    with open(settings.USER_DB+r'\%s.json'%name,'wt') as f:
        json.dump(user_dic,f)
        f.flush()


def query(name):
    '''查询用户信息'''
    db_path=settings.USER_DB+r'\%s.json'%name
    if os.path.isfile(db_path):
        with open(db_path,'rt') as f:
            res=json.load(f)
        return True,res
    else:
        return False, '用户不存在'


def query_log(name):
    '''查询日志功能'''
    with open(settings.OPE_LOG_PATH,'rt',encoding='utf-8') as f:
        for names in f.readlines():
            if name in names:
                print(names)
    with open(settings.TRA_LOG_PATH,'rt',encoding='utf-8') as f1:
        for names in f1.readlines():
            if name in names:
                print(names)

dbhandler.py

4858.com 174858.com 18

#:coding:utf-8
user_state = {'name': None}
from conf import settings
import logging.config
from db import dbhandler


def login_user():
    '''认证'''
    count = 0
    while True:
        name = input('请输入用户名:').strip()
        pwd = input('请输入密码:').strip()
        state, msg = dbhandler.query(name)
        if count == 3:
            print('您已被锁定')
            msg['lock'] = True
            dbhandler.save(msg)
            break
        if state:  # 查询状态
            if pwd == msg['password'] and not msg['lock']:
                user_state['name'] = name
                print('%s登录成功' % name)
                break
            elif msg['lock'] == True:
                print('您已被锁定')
                break
            else:
                count += 1
                print('密码错误%s次' % count)
        else:
            print(msg)
            break


def login_admin():
    '''管理员认证'''
    admin_dict = {'name': 'admin', 'password': '123', 'lock': False}
    name = input('请输入管理员账户:').strip()
    pwd = input('请输入密码:').strip()
    if name != admin_dict['name'] or pwd != admin_dict['password']:
        print('账号或密码错误')
    else:
        print('登录成功')
        user_state['name'] = name


def login_auth(auth='module'):
    def outter(func):
        '''装饰器'''

        def warppers(*args, **kwargs):
            if auth == 'user':
                if user_state['name'] == None:
                    login_user()
                if user_state['name']:
                    func(*args, **kwargs)
            if auth == 'admin':
                if user_state['name'] == None:
                    login_admin()
                if user_state['name'] == 'admin':
                    func(*args, **kwargs)
                else:
                    print('没有管理员权限!')
                    return

        return warppers

    return outter


def get_logger(name):
    '''日志模块'''
    logging.config.dictConfig(settings.LOGGING_DIC)
    logger = logging.getLogger(name)
    return logger

common.py

# coding:utf-8
# ================================start.py=======================================
import sys, os

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

from core import atm, shopping, admin


def menu():
    view = '''
        1.注册
        2.ATM     
        3.购物     
        4.管理员   
        q.退出
    '''
    print(view)


if __name__ == '__main__':
    view_dict = {
        '1': atm.registered,
        '2': atm.main,
        '3': shopping.main,
        '4': admin.main
    }
    while admin.tag:
        print('总界面'.center(60, '-'))
        menu()
        choice = input('请选择:').strip()
        if choice == 'q': break
        if not choice or choice not in view_dict: continue
        view_dict[choice]()

花了点时间将事先的面向进程编程作业重写了次,完结后觉得如故写的不够好。时间原因就没死扣了

                                  2018-09-05,16:03:47

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 美高梅手机版4858 版权所有