疫情环境下的网络学习笔记 python 3.29 小说阅读器

3.29 小说阅读器

bin

start.py

# start.py 存放启动文件

import os
import sys
from core import src

if __name__ == '__main__':
    src.run()

config

settings.py

# settings.py 用于存放配置文件,比如一些固定的路径

import os

# 主文件程序:deimos小说阅读器目录
BASE_PATH = os.path.dirname(os.path.dirname(__file__))

# db文件夹地址
DB_PATH = os.path.join(BASE_PATH,'db')

# db文件夹下db文件的地址
DB_TXT_PATH = os.path.join(DB_PATH,'db.txt')

# 目录存放地址
Album_path = os.path.join(DB_PATH,'album.txt')

AlBUM_DIR = os.path.join(DB_PATH, 'ALBUM')

core

src.py

# src.py 存放核心逻辑代码
import time
from db import db_handler
from lib import common

login_user = None


def register():
    while True:
        ipt_account = input('please enter your account(input "q" to quit this menu):').strip()
        if ipt_account == 'q':
            break
        else:
            # 检查数据库是否已经存在该账户,使用db_handler下的功能
            res = db_handler.getUserInfo(ipt_account)
            if res:
                print('account name has been used')
                continue
            else:
                # 让用户输入两次密码进行验证
                ipt_pwd = input('enter your password:').strip()
                re_ipt_pwd = input('reenter your password to confirm:').strip()
                # 验证后进入db_handler的功能,将数据写入文件
                if ipt_pwd == re_ipt_pwd:
                    db_handler.save_register(ipt_account, ipt_pwd)
                    print(f'{ipt_account} register succeed!')
                    break
                else:
                    print('two enters inconsistent, retry')


def login():
    while True:
        ipt_account = input('please enter your account (input "q" to quit current menu):').strip()
        res = db_handler.getUserInfo(ipt_account)
        if not res:
            print('account not exist, retry')
            continue
        ipt_pwd = input('please enter your password:').strip()
        if res[1] == ipt_pwd:
            global login_user
            login_user = ipt_account
            print(f'{ipt_account} login succeed!')
            break
        else:
            print('wrong password, retry')


@common.login_auth
def read_nov():
    Album_dic = db_handler.get_album_dic()
    # 如果为空,打印note
    if not Album_dic:
        print('No Album in station, please call Deimos')
        return
    while True:
        print('''
        ====welcome to my station====
            0 Sparrow 文雀乐队
            1 Chinese Football 国足
            2 LiZhi 李志
        ''')
        cmd2 = input("enter the musician you prefer:")
        if cmd2 not in Album_dic:
            print('enter a wrong musician num, retry')
            continue
        choice_album = Album_dic.get(cmd2)
        # 获取字典中对应的值
        # 对"0":["迷路记.txt",3],解压赋值
        for number, Album_list in choice_album.items():
            name, price = Album_list
            print(f'Album num: [{number}]  Album name: [{name}] Album price: [{price}]')
        while True:
            cmd3 = input('enter the num of album you prefer:')
            if cmd3 not in choice_album:
                print('enter a wrong num of album, retry')
                continue
            name, price = choice_album.get(cmd3)
            cmd4 = input(f'Buy[{name}] for [{price}]yuan, \n confirm? enter"Y":').strip()
            if cmd4 in ['Y', 'y']:
                # 从db中取信息,判断余额
                user, pwd, bal = db_handler.getUserInfo(login_user)
                bal = int(bal)
                price = int(price)

                if bal < price:
                    print('Insufficient balance, please charge')
                    break
                old_info = f'{user}:{pwd}:{bal}'
                bal -= price
                new_info = f'{user}:{pwd}:{bal}'
                # 用update 方法,新的replace旧的
                db_handler.update(old_info, new_info)
                print('purchase succeed!')
                album_data = db_handler.show_album(name)
                print(f'''
                strat playing...
                {album_data}
                ''')
                break
        break


@common.login_auth
def recharge():
    while True:
        charge_fee = input('please enter charge num:').strip()
        if not charge_fee.isdigit():
            print('please enter correct amount')
            continue
        charge_fee = int(charge_fee)
        # 通过getuserinfo获取用户数据
        user, pwd, bal = db_handler.getUserInfo(login_user)
        old_info = f'{user}:{pwd}:{bal}'
        # 对旧数据的余额进行 + 操作
        bal = int(bal)
        bal += charge_fee
        # 拼接新的info
        new_info = f'{user}:{pwd}:{bal}'
        db_handler.update(old_info, new_info)
        break
    print(f'[{login_user}] charge [{charge_fee}] succeed!')

    # 纪录日志


menu1 = {
    '0': ['quit', exit],
    '1': ['login', login],
    '2': ['register', register],
    '3': ['recharge', recharge],
    '4': ['start reading', read_nov]
}


def run():
    print("Welcome to Deimos's post-rock station")
    while True:
        for items in menu1:
            print(items, menu1[items][0])
        cmd1 = input('please enter command >>>')
        if cmd1 not in menu1:
            print('input a wrong command')
            continue
        menu1[cmd1][1]()

db

db_handler.py

# 用于操作数据库的代码

import os
from config import settings


# get user info:if exist in db.txt, return info of corrent account. else return None
def getUserInfo(user_account):
    with open(settings.DB_TXT_PATH, 'r', encoding='utf-8')as f:
        for i in f:
            if user_account in i:
                return i.strip('\n').split(':')


# append info to db.txt
def save_register(ipt_account, ipt_pwd, balance=0):
    with open(settings.DB_TXT_PATH, 'a', encoding='utf-8') as f:
        f.write(f'{ipt_account}:{ipt_pwd}:{balance}\n')


def update(old_info, new_info):
    # 先创建一个新文件
    new_path = os.path.join(settings.DB_PATH, 'new.txt')
    # 将修改过的数据存进new,再把new改名覆盖掉旧的
    with open(settings.DB_TXT_PATH, 'r', encoding='utf-8') as f, \
            open(new_path, 'w', encoding='utf-8') as g:
        # 用replace方法修改原文件
        all_user_info = f.read()
        all_user_info = all_user_info.replace(old_info, new_info)
        g.write(all_user_info)
    # rename行不通,还是先删除,再改名
    os.remove(settings.DB_TXT_PATH)
    os.rename(new_path, settings.DB_TXT_PATH)


def get_album_dic():
    with open(settings.Album_path,'r',encoding='utf-8') as f:
        Album_dic = eval(f.read())
        return Album_dic

def show_album(name):
    Album_path = os.path.join(settings.AlBUM_DIR,name)
    with open(Album_path,'r',encoding='utf-8') as f:
        album_data = f.read()
    return album_data

ALBUM

存放每一个album文件

db.txt

存放账户名,密码,余额

album.txt

album的目录

lib

common.py

# 存放公共功能,如装饰器
import os
from config import settings

def login_auth(func):
    from core import src

    def inner(*args, **kwargs):

        if src.login_user:
            res = func(*args, **kwargs)
            return res
        else:
            print('Login before operation...')
            src.login()

    return inner

log

README

猜你喜欢

转载自www.cnblogs.com/telecasterfanclub/p/12591695.html