欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

练手小程序用了pandas模块和json模块以及time模块

程序员文章站 2022-06-29 08:10:11
6.16自我总结 功能介绍 1.程序设计目录 2. 3. 3. 4. 5. (商品信息存储文件与功能模块的交互) 6. (用户信息存储文件与功能模块的交互) 7.goods_info.xlsx/goods_info_patch.xlsx ||苹果|香蕉|西瓜|荔枝|梨| |: :|: :|: :|: ......

6.16自我总结

功能介绍

程序功能介绍:
    商品信息再读取修改买卖均已xlsx格式
    且生成购物记录也按/用户名/购买时间.xlsx格式生成
    账号密码输入错误三次按照时间进行冻结
    用户信息已json格式保存
 程序写的过程
先生成功能模块和运行模块
再写功能模块中用到的固定的文件目录全放在setting.py文件中
与商品交互全放在shop.py中
与用户交互全放在user.py中
一些返回界面延迟动画全放在辅助模块中

1.程序设计目录

练手小程序用了pandas模块和json模块以及time模块

2.run.py

from core.src import run
if __name__ == '__main__':
    run()

3.src.py

from conf.setting import *
from lib.common import *
from api.user import *
from api.shop import *
import re

import numpy as np

goods_count = [1]
#注册
def register():
    print('\033[47;;m\t\t欢迎使用注册功能\t\t\033[0m')
    count = 0
    while count == 0:
        register_name = input('请输入名字按q退出程序\n'
                              '\033[31;;m账号由汉字,字母,数字,下划线组成\033[0m'
                              '\n请输入:')
        if register_name == 'q':
            go_to_run()
            return false
        if decide_user_name(register_name):
            print('\033[31;;m账号存在\033[0m')
            continue
        register_name_1 = re.findall('\w+',register_name)
        if len(register_name) == 0:
            print('\033[31;;m请好好输入\033[0m')
            continue
        elif register_name_1[0] != register_name:
            print('\033[31;;m账号由汉字,字母,数字,下划线组成\033[0m')
            continue
        else:
            count =1
            while true:
                register_pwd = input('请输入密码按q退出程序\n'
                                     '\033[31;;m密码由汉字,字母,数字,下划线组成\033[0m\n'
                                     '请输入')
                if register_pwd == 'q':
                    go_to_run()
                    return false
                register_pwd_1 = re.findall('\w+', register_pwd)
                if len(register_pwd) == 0:
                    print('\033[31;;m请好好输入\033[0m')
                    continue
                elif register_pwd_1[0] != register_pwd:
                    print('\033[31;;m密码由汉字,字母,数字,下划线组成\033[0m')
                    continue
                else:
                    save_info(register_name, register_pwd)
                    print('\033[32;;m注册成功\033[0m')
                    go_to_run()
                    return true

#登入
def login():
    print('\033[47;;m\t\t欢迎使用登入功能\t\t\033[0m')
    if not login_name[0]:
        pwd_count =0
        login_count = 0
        while login_count==0:
            login_name = input('请输入名字按q退出程序\n请输入:')
            if login_name == 'q':
                go_to_run()
                return false
            if not decide_user_name(login_name):
                print('\033[31;;m账号不存在\033[0m')
                continue
            if not load_freeze_user(login_name):
                go_to_run()
                return false
            else:
                login_count = 1
                while pwd_count<3:
                    login_pwd = input('\033[41;;m请输入密码输错三次会被冻结五分钟\033[0m\n请输入:')
                    if not load_info(login_name,login_pwd):
                        pwd_count +=1
                        print(f'\033[31;;m还有{3-pwd_count}次机会\033[0m')
                        continue
                    else:
                        print('\033[32;;m登入成功\033[0m')
                        login_name[0] = login_name
                        go_to_run()
                        return true
                if pwd_count == 3:
                    freeze_user(login_name)
                    print(f'\033[31;;m账号{login_name}由于密码输入太多次暂时被冻结\033[0m')
                    go_to_run()
                    return false
    else:
        print(f'\033[32;;m账号{login_name[0]}以及登入')
        login_chiose = input('输入0为退出当前程序\n'
                             '输入1为退出当前账号重新登入\n'
                             '输入2为退出当前账号并退出程序\n'
                             '请选择:')
        if login_chiose not in ['0','1','2']:
            print('\033[31;;m请好好输入\033[0m')
        elif login_chiose == '0':
            go_to_run()
            return false
        elif login_chiose == '1':
            df = load_goods_pach()
            dump_goods(df)
            login_name[0] = none
            login()
        elif login_chiose == '2':
            df = load_goods_pach()
            dump_goods(df)
            login_name[0] = none
            print('\033[41;;m账号以退出\033[0m')
            go_to_run()
            return false

#充值
@login_deco
def top_up():
    print('\033[47;;m\t\t欢迎使用充值功能\t\t\033[0m')
    while true:
        chiose = input('请输入充值金额\n输入q退出功能\n请输入')
        if chiose  == 'q':
            go_to_run()
            return false
        elif not chiose.isdigit():
            print('\033[31;;m请输入阿拉伯数字\033[0m')
            continue
        else:
            info = load_login_info(login_name[0])
            info["balance"] += int(chiose)
            dump_login_info(login_name[0],info)
            print(f'\033[42;;m账号{login_name[0]}充值成功\n当前余额{info["balance"]}元\033[0m')
            go_to_run()
            return true

#余额查询
@login_deco
def balance():
    print('\033[47;;m\t\t欢迎使用余额查询功能\t\t\033[0m')
    info = load_login_info(login_name[0])
    print(f'\033[42;;m账号{login_name[0]}\n当前余额{info["balance"]}\033[0m')
    go_to_run()
    return true

#提现
@login_deco
def withdraw():
    print('\033[47;;m\t\t欢迎使用提现功能\t\t\033[0m')
    while true:
        chiose = input('\033[32;;m请输入提现金额\n输入q退出功能\n请输入')
        if chiose  == 'q':
            go_to_run()
            return false
        elif not chiose.isdigit():
            print('\033[31;;m请输入阿拉伯数字\033[0m')
            continue
        else:
            info = load_login_info(login_name[0])
            if info["balance"] < int(chiose):
                print('\033[31;;m余额不足\033[0m')
                continue
            info["balance"] -= int(chiose)
            dump_login_info(login_name[0],info)
            print(f'\033[41;;m账号{login_name[0]}提现成功\n当前余额{info["balance"]}元\033[0m')
            go_to_run()
            return true

#转账
@login_deco
def transfer():
    print('\033[47;;m\t\t欢迎使用转账功能\t\t\033[0m')
    count = 0
    while count ==0:
        chiose = input('\033[32;;m请输入转账金额\n输入q退出功能\n请输入')
        if chiose  == 'q':
            go_to_run()
            return false
        elif not chiose.isdigit():
            print('\033[31;;m[请输入阿拉伯数字\033[0m')
            continue
        else:
            info = load_login_info(login_name[0])
            if info["balance"] < int(chiose):
                print('\033[31;;m余额不足\033[0m')
                continue
            info["balance"] -= int(chiose)

            while true:
                count =1
                transfer_name = input('\033[32;;m转账的名字\n输入q退出')
                if transfer_name == 'q':
                    go_to_run()
                    return false
                if not decide_user_name(transfer_name):
                    print('\033[31;;m转账账号不存在\033[0m')
                    continue
                if login_name[0] == transfer_name:
                    print('\033[31;;m不能转给自己\033[0m')
                    continue
                transfer_name_info = load_login_info(transfer_name)
                transfer_name_info["balance"] += int(chiose)
                dump_login_info(transfer_name, transfer_name_info)
                dump_login_info(login_name[0], info)
                print(f'\033[42;;m账号{login_name[0]}转账成功\n当前余额{info["balance"]}元\033[0m')
                go_to_run()
                return true

#流水
@login_deco
def user_history():
    print('\033[47;;m\t\t欢迎使用流水功能\t\t\033[0m')
    if not history(login_name[0]):
        print('\033[31;;m没有购买记录\033[0m')
        go_to_run()
        return false
    while true:
        date_lis = show_history(login_name[0])
        chiose = input('\033[32;;m请输入你要查看的日期\n'
                       '输入q退出')
        if chiose not in date_lis:
            print('\033[31;;m没有日期\033[0m')
            continue
        print(f'{chiose}')
        print(load_goods_history(login_name[0],chiose))
        history_count = 0
        while history_count == 0:
            next_chiose = input('\033[32;;m请输入y继续查看的日期\n'
                                '输入q退出\n'
                                '请输入')
            if next_chiose not in ('y','q'):
                print('\033[31;;m请好好输入\033[0m')
            elif next_chiose == 'y':
                history_count =1
            elif next_chiose =='q':
                go_to_run()
                return false
#购物
@login_deco
def shopping():
    count = 0
    chiose_count =0
    print('\033[47;;m\t\t欢迎使用购物功能\t\t\033[0m')
    global goods_count
    while count == 0:
        if not goods_count[0]:
            df = load_goods()
            print('\t\t\t商品目录')
            print(f'\033[35;36;m{df}\033[0m')
        else:
            df = load_goods_pach()
            print('\t\t\t商品目录')
            print(f'\033[35;36;m{df}\033[0m')

        goods = input('\033[32;;m请选择你的商品\n'
                      '输入q退出\n'
                      '请选择')
        goods_list = df.columns
        if goods == 'q':
            go_to_run()
            return false
        elif goods not in goods_list:
            print('\033[31;;m无此商品\033[0m')
            continue
        else:
            chiose_count =0
            while chiose_count == 0:
                num = input('\033[32;;m请选择你的商品数量\n'
                              '输入q退出\n'
                            '请选择')
                goods_num = df[goods]['数量']
                if goods == 'q':
                    go_to_run()
                    return false
                elif not num.isdigit():
                    print('\033[31;;m请输入数字\033[0m')
                    continue
                elif int(goods_num)<int(num):
                    print('\033[31;;m库存不足\033[0m')
                else:
                    df[goods]['数量'] -= int(num)
                    goods_num = int(num)
                    dump_goods_pach(df)
                    print(f'\033[42;;m你把{goods}{num}个加入购物车\033[0m')
                    while chiose_count == 0:
                        chiose =input('\033[32;;m是否继续购物\n'
                                      'y是继续,n是退出\n'
                                      '请选择')
                        if chiose not in ['y','n']:
                            print('\033[31;;m请好好输入\033[0m')
                            continue
                        if chiose == 'n':

                            goods_count[0] = 1
                            go_to_run()
                            return true
                        if chiose == 'y':
                            chiose_count = 1
                            goods_count[0] = 1
                            pass




#购物车
@login_deco
def shopping_car():
    print('\033[47;;m\t\t欢迎使用购物车功能\t\t\033[0m')
    global goods_count
    if not goods_count[0]:
        print('\033[31;;m购物车无商品\033[0m')
    else:
        df_1 = load_goods()
        df_2 = load_goods_pach()
        df = df_1 - df_2
        print('-'*50)
        print('\t\t\t购物车目录')
        print(f'\033[35;36;m{df}\033[0m')
        df_mun = df.values[1,:]
        df_pice = df_1.values[0,:]
        df_add = df_mun*df_pice
        money = sum(df_add)
        print(f'合计{money}元')
        print('-' * 50)
        while true:
            chiose = input('\033[32;;m输入q退出程序\n'
                           '输入0清空购物车并退出程序\n'
                           '输入1结算\n'
                           '请选择')
            if chiose not in ['q','0','1']:
                print('\033[31;;m请好好输入\033[0m')
                continue
            elif chiose == 'q':
                go_to_run()
                return false
            elif chiose == '0':
                goods_count[0] = none
                df_new = load_goods()
                dump_goods_pach(df_new)
                go_to_run()
                return false
            elif chiose == '1':
                info = load_login_info(login_name[0])
                if int(money) > info['balance']:
                    print('\033[31;;m余额不足\033[0m')
                    continue
                else:
                    print('\033[41;;m支付成功\033[0m')
                    info['balance'] -= int(money)
                    dump_login_info(login_name[0],info)
                    df_new = load_goods_pach()
                    dump_goods(df_new)
                    df_mun = df[1:2]
                    df_pice = df_1[0:1]
                    df = df.columns
                    new_df = df_pice.append(df_mun)
                    print(new_df)
                    time =time_strftime()
                    dump_goods_history(login_name[0],time,new_df)
                    go_to_run()
                    return true











#运行模块
def run():
    action_dict={
        '0':register,
        '1':login,
        '2':top_up,
        '3':balance,
        '4':withdraw,
        '5':transfer,
        '6':user_history,
        '7':shopping,
        '8':shopping_car,
    }

    while true:
        if login_name[0]:
            print(f'你好{login_name[0]}')
        for action_num,action in action_info.items():
            print(f'\033[35;;m\t\t输入{action_num}功能为{action}\033[0m')
        action_chiose = input('\033[32;;m请输入你要选择的功能:')
        if action_chiose == 'q':
            print('退出程序')
            return
        if action_chiose not in action_dict:
            print('\033[31;;m输入错误\033[0m')
            continue
        action_dict[action_chiose]()

if __name__ == '__main__':
    run()

3.common.py

from conf.setting import *
import time

def login_deco(func):
    def wrapper(*args,**kwargs):
        if not login_name[0]:
            print('请先登入')
            go_to_run()
            return false
        func()
        return true
    return wrapper

def go_to_run():
    for a in range(20):
        time.sleep(0.1)
        txt = '\t\t返回主界面中'
        txt += '.'*int(a%4)
        print('\r',f'\033[32;;m{txt}\033[0m',end='')
    print('')

def time_now():
    return time.time()

def time_strftime():
    return str(time.strftime('%y-%m-%d-%h-%m-%s'))

4.setting.py

import os
import time
action_info={
        '0':'注册',
        '1':'登入',
        '2':'充值',
        '3':'余额查询',
        '4':'提现',
        '5':'转账',
        '6':'购物历史记录',
        '7':'购物',
        '8':'购物车',
        'q' :'退出'
    }

login_name = [none]


atm_path = os.path.dirname(os.path.dirname(__file__))
user_path = os.path.join(atm_path,'db')
goods_path = os.path.join(atm_path,'db','goods_info.xlsx')
goods_patch = os.path.join(atm_path,'db','goods_info_patch.xlsx')

5.shop.py

(商品信息存储文件与功能模块的交互)

import pandas as pd
from conf.setting import goods_path,goods_patch
import os

def dump_goods(df):
    df.to_excel(goods_path)

def dump_goods_pach(df):
    df.to_excel(goods_patch)

def load_goods():
    df = pd.read_excel(goods_path,index_col=0,header=0)
    return df
def load_goods_pach():
    df = pd.read_excel(goods_patch,index_col=0,header=0)
    return df

def dump_goods_history(name,time,df):
    path_1 = os.path.join(r'e:\atm\db', name)
    path = os.path.join(r'e:\atm\db',name,f'{time}.xlsx')
    if not os.path.exists(path_1):
        os.mkdir(path_1)
    df.to_excel(path)

def load_goods_history(name,time):
    path = os.path.join(r'e:\atm\db', name, f'{time}.xlsx')
    df = pd.read_excel(path,index_col=0,header=0)
    return df

def show_history(name):
    new_list =[]
    path_1 = os.path.join(r'e:\atm\db', name)
    lis = os.listdir(path_1)
    print('\033[46;;m提示:年-月-日-时-分-秒\033[0m')
    for info in lis:
        info = info[0:-5]
        print(info)
        new_list.append(info)
    return new_list

def history(name):
    path_1 = os.path.join(r'e:\atm\db', name)
    if os.path.exists(path_1):
        return true
    return false
if __name__ == '__main__':
    df = load_goods_pach()
    print(df)

6.user.py

(用户信息存储文件与功能模块的交互)

from conf.setting import *
import json
import hashlib
from lib.common import time_now

def save_info(user_name,pwd):
    m = hashlib.md5()
    m.update(pwd.encode('utf8'))
    pwd =m.hexdigest()
    user_path = os.path.join(user_path, f'{user_name}.json')
    with open(user_path,'w',encoding='utf8') as fw:
        info_dict = {'name':user_name,'pwd':pwd,'freeze':time_now(),'balance':0,'freeze_count':0}
        json.dump(info_dict,fw)

def load_info(user_name,pwd):
    user_path = os.path.join(user_path, f'{user_name}.json')
    if not login_name[0]:
        if not os.path.exists(user_path):
            print('\033[31;;m用户不存在\033[0m')
            return false
        m = hashlib.md5()
        m.update(pwd.encode('utf8'))
        pwd =m.hexdigest()
        with open(user_path, 'r', encoding='utf8') as fr:
            info_dict = json.load(fr)
        if info_dict.get('pwd') != pwd:
            print('\033[31;;m密码错误\033[0m')
            return false
    with open(user_path, 'r', encoding='utf8') as fr:
        info_dict = json.load(fr)
    info_dict['freeze_count'] = 0
    with open(user_path, 'w', encoding='utf8') as fw:
        json.dump(info_dict,fw)
    return info_dict

def decide_user_name(user_name):
    user_path = os.path.join(user_path, f'{user_name}.json')
    if  os.path.exists(user_path):
        return true
    return false

def freeze_user(user_name):
    user_path = os.path.join(user_path, f'{user_name}.json')
    with open(user_path, 'r', encoding='utf8') as fr:
        info_dict = json.load(fr)
    info_dict['freeze_count'] += 1
    info_dict['freeze'] = time_now() + 300*info_dict['freeze_count']
    with open(user_path,'w',encoding='utf8') as fw:
        json.dump(info_dict,fw)

def load_freeze_user(user_name):
    user_path = os.path.join(user_path, f'{user_name}.json')
    with open(user_path, 'r', encoding='utf8') as fr:
        dict = json.load(fr)
    if time_now() >= dict['freeze'] :
        print('\033[32;;m账号登入成功\033[0m')
        return true
    else:
        min = int(divmod(-time_now() + dict['freeze'], 60)[0])
        s = int(divmod(-time_now() + dict['freeze'], 60)[1])
        print(f'\033[31;;m账号{user_name}已被冻结,还需要{min}分{s}秒\033[0m')
        return false

def load_login_info(name):
    login_user_path = os.path.join(user_path, f'{name}.json')
    with open(login_user_path, 'r', encoding='utf8') as fr:
        info_dict = json.load(fr)
    return info_dict

def dump_login_info(name,dict):
    login_user_path = os.path.join(user_path, f'{name}.json')
    with open(login_user_path, 'w', encoding='utf8') as fw:
        json.dump(dict,fw)
        return true

if __name__ == '__main__':
    save_info('杨文益','12312')
    dict = load_info('杨文益','12312')
    print(dict['name'])

7.goods_info.xlsx/goods_info_patch.xlsx

苹果 香蕉 西瓜 荔枝
价格 2 3 10 5 5
数量 200 215 34 32 523