Python模拟简单的博客注册登录系统

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

编程思想:
1.把复杂的问题简单化:函数式编程:一步一函数!
2.逻辑清晰,目标明确,方便测试部分功能
3.设计、分析实现的方式 有一个清晰的实现的数据框架

# 首先确定一个存储用户注册信息的文件--使用--?怎么取数据比较方便?建立一个明确的数据结构来存储用户的注册数据
# 明确的数据结构来存储用户的注册数据
from datetime import datetime
import os, sys
import json

userDictTable = {"users":[{"username":"admin","password":"123456"}]}
# print(userDictTable,type(userDictTable))
# print(userDictTable["users"])
    
newUser = {"username":"manager","password":"654321"}
userDictTable["users"].append(newUser)
# print(userDictTable)
    
# for i in userDictTable["users"]:
    # print(i["username"])
    # print(i["password"])

# 1.创建一个用户表结构文件,可以读取用户注册的信息
def readAllUser(path="user.json"):
    # 用户表结构文件存在
    if os.path.exists(path):
        # 存在,读取信息
        with open(path) as f_r:
            # 读取到的内容
            return json.load(f_r)
    else:
        with open(path, "w")as f_w:
            userDictTable = {"users": [{"username": "admin", "password": "123456"}]}
            json.dump(userDictTable, f_w)
            print("创建默认用户表结构成功!")
            return userDictTable

#函数式编程,在写完一个功能模块后,要测试当前功能是都能够正确运行
# x = readAllUser()
# print(x)

# 2.更新注册用户表信息:全部覆盖更新写入!
def updateUserTable(userDict, path="user.json"):
    """
    :param userDict: 全部的用户数据
    :param path: 文件路径
    :return:
    """
    with open(path, "w") as f_w:
        json.dump(userDict, f_w)
        print("用户配置表更新成功!")


# updateUserTable({"users":[{"username":"admin","password":"123456"},
#                           {"username":"manager","password":"654321"}]})

# 创建文件用来读取文章信息
def createDefaultArticle(name, path="Article"):
    if os.path.exists(path):
        # 不存在,创建一个默认的文章
        with open(os.path.join(path, name + ".json"), "w") as f_w:
            # 默认的文章
            articleDictTable = {"articles": [{
                "title": "default title",
                "author": name,
                "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "content": "welcome to my blog!"
            }]}
            json.dump(articleDictTable, f_w)
            return articleDictTable
            print("创建默认文章成功!")
    else:
        os.mkdir(path)
        # 不存在,创建一个默认的文章
        with open(os.path.join(path, name + ".json"), "w") as f_w:
            # 默认的文章
            articleDictTable = {"articles": [{
                "title": "default title",
                "author": name,
                "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "content": "welcome to my blog!"
            }]}
            json.dump(articleDictTable, f_w)
            return articleDictTable
            print("创建默认文章成功!")


# createDefaultArticle("jake")


# 3.账号注册:用户名存在--》注册失败,不存在,注册成功!
def register(path="user.json"):
    while True:
        username = input("【注册】请输入用户名:")
        password = input("【注册】请输入密码:")

        # 从注册用户表中拿到用户信息
        temp = readAllUser(path)
        # print(temp)
        isExists = False  # 默认用户名不存在: 加小旗子 flag
        # 匹配判断用户名是否存在
        for i in temp["users"]:
            # print(i)
            if i["username"] == username:
                # 用户名存在
                isExists = True
                break
        if isExists == False:  # 用户名不存在,注册
            # 创建一个字典存储用户注册信息
            curUser = {"username": username, "password": password}
            # 增加到用户表结构中
            temp["users"].append(curUser)
            # 更新用户注册信息文件
            updateUserTable(temp, path)
            print("注册成功!")
            createDefaultArticle(username)
            return True


# x = register()
# print(x)

# 4.登陆验证:用户名 and 密码 right--》successfully!!!
def login(path="user.json"):
    global currentUser
    while True:
        username = input("【登录】请输入用户名:")
        password = input("【登录】请输入密码:")

        # 获取注册表信息
        temp = readAllUser(path)
        isFind = False  # 默认没找到
        for i in temp["users"]:
            # 判断用户名和密码
            if i["username"] == username and i["password"] == password:
                # 登录成功!
                isFind = True
                print("登录成功!")
                currentUser = username
                return isFind  # 登录成功的结果
        if isFind == False:
            print("用户名或密码错误!")


# x = login()
# print(x)

# 5.确定文章的表结构
articleDictTable = {"articles": [{
    "title": "default title",
    "author": "default author",
    "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    "content": "default content"
}]}


# 读取用户的文章
def readAllArticle(name, path="Article"):
    with open(os.path.join(path, name + ".json")) as f_r:
        return json.load(f_r)


# x = readAllArticle("chengcheng")
# print(x)

# 更新文章信息:全部覆盖更新写入!!!
def updateArticle(name, articleDict, path="Article"):
    with open(os.path.join(path, name + ".json"), "w") as f_w:
        json.dump(articleDict, f_w)
        print("更新文章成功!")


# newArticle = {'title': 'test',
#               'author': 'chengcheng',
#               'time': '2019-09-15 15:21:48',
#               'content': 'test updateArticle'}
# allArticle = readAllArticle("chengcheng")
# print(allArticle)
# allArticle["articles"].append(newArticle)
# print(allArticle)
# updateArticle("chengcheng",allArticle)

# 2.写文章,包含【标题,作者,时间,内容】
def writeArticle(name, path="Article"):
    print("开始写文章啦啦啦啦啦".center(50, "*"))
    title = input("请输入文章标题:")
    content = input("请输入文章内容:")

    # 创建数据结构存储文章信息
    articleDict = {
        "title": title,
        "author": name,
        "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "content": content
    }

    # 读取文章信息,用于追加
    allArticle = readAllArticle(name, path)
    allArticle["articles"].append(articleDict)

    # 调用更新文章数据
    updateArticle(name, allArticle, path)


# writeArticle("chengcheng")

# 3.查询文章,列出所有文章及时间
def findAllArticle(name, path="Article"):
    all = readAllArticle(name, path)
    # print(all)
    for i in range(len(all["articles"])):
        # 文章的下标
        # print(i)
        print(i + 1, "文章的标题是:%s,文章的时间是:%s" % (all["articles"][i]["title"],
                                              all["articles"][i]["time"]))


# findAllArticle("chengcheng")

# 4.可查看其中一篇文章
def findOneArticle(name, path="Article"):
    all = readAllArticle(name, path)
    print(all)
    for i in range(len(all["articles"])):
        # 文章的下标
        # print(i)
        print(i + 1, "文章的标题是:%s,文章的时间是:%s" % (all["articles"][i]["title"],
                                              all["articles"][i]["time"]))
    index = int(input("请输入你要查看文章的编号:"))
    print("文章的作者是:%s,文章内容是:%s" % (all["articles"][index - 1]["author"],
                                  all["articles"][index - 1]["content"]))


# findOneArticle("chengcheng")

# 5.删除文章
def deleteArticle(name, path="Article"):
    all = readAllArticle(name, path)
    for i in range(len(all["articles"])):
        print(i + 1, "文章的标题是:%s,文章的时间是:%s" % (all["articles"][i]["title"],
                                              all["articles"][i]["time"]))
    index = int(input("请输入你要删除文章的编号:"))
    if len(all["articles"]) > 0:
        # 删除文章
        all["articles"].pop(index - 1)

        # 更新文章表数据
        updateArticle(name, all, path)
        print("删除文章成功!")
    else:
        print("没有文章可供操作!")


# deleteArticle("chengcheng")

# 6.修改文章
def editArticle(name, path="Article"):
    all = readAllArticle(name, path)
    for i in range(len(all["articles"])):
        print(i + 1, "文章的标题是:%s,文章的时间是:%s" % (all["articles"][i]["title"],
                                              all["articles"][i]["time"]))
    index = int(input("请输入你要修改文章的编号:"))
    if len(all["articles"]) > 0:
        # 修改文章
        print("开始修改文章:".center(50, "*"))
        title = input("请输入文章标题:")
        content = input("请输入文章内容:")
        # 创建数据结构存储文章信息
        articleDict = {
            "title": title,
            "author": name,
            "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "content": content
        }
        # 修改的文章把原有的文章覆盖
        all["articles"][index - 1] = articleDict
        print(all["articles"][index - 1])
        print(all["articles"])

        # 更新文件中的数据
        updateArticle(name, all, path)
    else:
        print("你要操作的文章不存在!")


# editArticle("chengcheng")

# 声明一个全局变量
currentUser = ""


def Main():
    # 引入全局变量
    global currentUser
    print("欢迎来到富丽豪华功能强大的博客系统".center(50, "*"))
    while True:
        selectA = input("请输入:1.注册 2.登录 3.退出")
        if selectA == "1":
            register()
        elif selectA == "2":
            if login():
                while True:
                    # 登陆成功!
                    selectB = input("请输入:1.写文章 2.查看全部文章 3.查看其中一篇文章"
                                    " 4.删除文章 5.修改文章 6.退出登录")
                    if selectB == "1":
                        writeArticle(currentUser)
                    elif selectB == "2":
                        findAllArticle(currentUser)
                    elif selectB == "3":
                        findOneArticle(currentUser)
                    elif selectB == "4":
                        deleteArticle(currentUser)
                    elif selectB == "5":
                        editArticle(currentUser)
                    else:
                        currentUser = ""
                        break

        else:
            print("欢迎下次光临!")
            sys.exit()


Main()
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值