python一个简单的博客系统

博客系统


前言

模拟简单的博客
1.账号注册,登陆验证
2.写文章,包含【标题,作者,时间,内容】
3.查询文章,列出所有文章及时间
4.可查看其中一篇文章
5.删除文章
6.修改文章
7.退出系统


全部代码如下

import json
import os
import sys
from datetime import datetime


class User:

    def __init__(self, name, pwd) -> None:
        self.name = name
        self.pwd = pwd

    @property
    def pwd(self):
        return self._pwd

    @pwd.setter
    def pwd(self, value):
        self._pwd = value

        if len(value) < 6:
            val = input("用户密码过于简单,再次输入?")
            self.pwd = val
        else:
            re_pwd = input("再次输入用户密码?")
            if re_pwd == value:
                self._pwd = value

    # 将对象返回 dict
    def show(self):
        return {
    
    'name': self.name, 'pwd': self.pwd}


class UserManager:
    # 用户配置表 路径
    user_path = 'user.json'

    # 当前登录的用户
    cur_user = None

    # 唯一实例
    instance = None

    def __new__(cls):
        if cls.instance == None:
            cls.instance = super().__new__(cls)
        return cls.instance

    # 读取用户配置表
    def read_user_json(self):

        if os.path.exists(self.user_path):
            # 用户配置文件存在
            with open(self.user_path, encoding='utf-8') as f_r:
                return json.load(f_r)
        else:
            # 用户配置文件不存在
            user_j = {
    
    "users": []}
            with open(self.user_path, 'w', encoding='utf-8') as f_w:
                json.dump(user_j, f_w)
            return user_j

    # 写入用户配置表
    def write_user_json(self, user):
        # 读取所有的用户
        all_user = self.read_user_json()
        all_user['users'].append(user.show())
        # 写出去
        with open(self.user_path, 'w', encoding='utf-8') as f_w:
            json.dump(all_user, f_w)
            print("更新成功!!")

    # 查找用户
    def find_user_json(self, user):
        # 读取所有的用户
        all_user = self.read_user_json()
        # 遍历查找 是否存在用户
        for i in all_user['users']:
            if i['name'] == user.name:
                return [True, i]
        else:
            return [False]

    # 注册
    def register(self):
        print("正在注册".center(50, '*'))
        name = input("请输入注册的用户名?")
        pwd = input(f'请输入{name}的密码?')

        # 创建新用户
        u = User(name, pwd)
        if self.find_user_json(u)[0]:
            print("用户已经存在!,注册失败!")
            return False
        else:
            print("注册中,请稍后!")
            self.write_user_json(u)
            print("注册成功!")
            ArticleManager().create_default_article(name)
            return True

    # 登录
    def login(self):
        print("正在登录".center(50, '*'))
        name = input("请输入登录的用户名?")
        pwd = input(f'请输入{name}的密码?')
        # 创建新用户
        u = User(name, pwd)
        f_user = self.find_user_json(u)
        if f_user[0]:
            print("用户存在!判断密码")
            if f_user[1]['pwd'] == pwd:
                print("登录成功!")
                UserManager.cur_user = name
                return True
            else:
                return False
        else:
            print("登录失败")
            return False


class Article:

    def __init__(self, title, content, author) -> None:
        self.title = title  # 文章标题
        self.content = content  # 文章内容
        self.time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 时间
        self.author = author  # 作者

    def show(self):
        return {
    
    'title': self.title, 'time': self.time, "author": self.author, "content": self.content}


class ArticleManager:
    # 文章的路径
    article_path = 'article'

    # 静态实例
    instance = None

    def __new__(cls):
        if cls.instance == None:
            cls.instance = super().__new__(cls)
        return cls.instance

    def __init__(self) -> None:
        # 创建目录文件夹
        if not os.path.exists(self.article_path):
            os.mkdir(self.article_path)

    # 创建默认
    def create_default_article(self, name):
        # 用于创建默认文章表
        art_json_path = os.path.join(self.article_path, name + '.json')
        with open(art_json_path, 'w', encoding='utf-8') as f_r:
            temp = {
    
    'articles': [Article('初始化默认标题', '初始化默认内容', name).show()]}
            json.dump(temp, f_r, ensure_ascii=False)
            print("默认文章表创建完成!")

    # 读取用户文章
    def read_article_json(self):
        self.art_json_path = os.path.join(self.article_path, UserManager.cur_user + '.json')
        with open(self.art_json_path, encoding='utf-8') as f_r:
            return json.load(f_r)

    # 写入用户文章
    def write_article_json(self, all_article):
        self.art_json_path = os.path.join(self.article_path, UserManager.cur_user + '.json')
        with open(self.art_json_path, 'w', encoding='utf-8') as f_w:
            json.dump(all_article, f_w)
            print("更新文成功!")

    # 写文章
    def write_article(self):
        print("写一篇文章".center(50, '*'))
        title = input('请输入标题?')
        content = input('请输入内容?')
        # 文章对象
        art = Article(title, content, UserManager.cur_user)
        # 读取所有文章
        all_article = self.read_article_json()
        # 追加文章
        all_article['articles'].append(art.show())
        # 写文章
        self.write_article_json(all_article)
        print('发表文章成功!')
        print("写一篇文章".center(50, '*'))

    # 查所有
    def find_all(self):
        print("查找所有文章".center(50, '*'))
        all_article = self.read_article_json()
        for i in range(len(all_article['articles'])):
            title = all_article['articles'][i]['title']
            if len(title) > 8:
                title = title[:7] + '...'
            else:
                title = title.ljust(10, ' ')

            print(i + 1, title, all_article['articles'][i]['time'])

        print("查找所有文章".center(50, '*'))
        return all_article

    # 查一篇
    def find_one(self):

        all_article = self.find_all()
        print("查找一篇文章".center(50, '*'))
        index = int(input('请输入您要查看的序号?'))
        if 0 <= index <= len(all_article['articles']):
            print(all_article['articles'][index - 1])
        else:
            print("序号错误!")
        print("查找一篇文章".center(50, '*'))

    # 编辑一篇
    def edit_article(self):

        all_article = self.find_all()
        print("编辑一篇文章".center(50, '*'))
        index = int(input('请输入您要编辑的序号?'))
        if 0 <= index <= len(all_article['articles']):
            title = input('请输入新的标题?')
            content = input('请输入新的内容?')
            # 文章对象
            art = Article(title, content, UserManager.cur_user)
            # 更改文章
            all_article['articles'][index - 1] = art.show()
            # 写文章
            self.write_article_json(all_article)
            print('修改文章成功!')

        else:
            print("序号错误!")
        print("编辑一篇文章".center(50, '*'))

    # 删除一篇
    def delete_article(self):
        all_article = self.find_all()
        print("删除一篇文章".center(50, '*'))
        index = int(input('请输入您要编辑的序号?'))
        if 0 <= index <= len(all_article['articles']):

            # 删除文章
            all_article['articles'].pop(index - 1)
            # 写文章
            self.write_article_json(all_article)
            print('删除文章成功!')

        else:
            print("序号错误!")
        print("删除一篇文章".center(50, '*'))


def main():
    print("欢迎来到XXX皇家豪华博客系统".center(50, '*'))
    while True:
        select_a = input("1注册 2登录 3退出")
        if select_a == '1':
            UserManager().register()
        elif select_a == '2':
            if UserManager().login():
                while True:
                    select_b = input("1写文章 2读取所有 3读取一篇 4编辑一篇 5删除一篇 6登出")
                    if select_b == '1':
                        ArticleManager().write_article()
                    elif select_b == '2':
                        ArticleManager().find_all()
                    elif select_b == '3':
                        ArticleManager().find_one()
                    elif select_b == '4':
                        ArticleManager().edit_article()
                    elif select_b == '5':
                        ArticleManager().delete_article()
                    else:
                        break
        else:
            sys.exit()


if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/qq_41186565/article/details/115028836