33-1-装饰器博客园带评论
2020年12月14日大约 2 分钟
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Meet"
# Date: 2019-07-29
import json
import os
msg = """
1.请登录
2.请注册
3.进入文章页面
4.进入评论页面
5.进入日记页面
6.进入收藏页面
7.注销账号
8.退出整个程序
>>>
"""
login_dic = {
"username": None,
"flag": False,
"count": 3
}
def auth(func):
def inner(*args, **kwargs):
if login_dic['flag']:
ret = func(*args, **kwargs)
return ret
else:
login(func)
return inner
def login(func=False):
"""
登录
:return:
"""
print("欢迎进入登录页面")
while login_dic["count"]:
username = input("username:")
password = input("password:")
f1 = open("error_userninfo", "r+", encoding="utf-8")
for i in f1:
if json.loads(i).get(username) == 3:
print("用户名锁定!")
login_dic['count'] = 0
break
else:
with open("userinfo", "r", encoding="utf-8")as f:
for i in f:
user, pwd = i.strip().split(":")
if user == username and pwd == password:
print("登录成功")
login_dic["count"] = 0
login_dic["username"] = user
login_dic["flag"] = True
if func:
func()
break
else:
login_dic["count"] -= 1
f1.seek(0)
for user in f1:
error_dic = json.loads(user)
if username in error_dic:
if error_dic.get(username) < 3:
error_dic[username] += 1
if error_dic[username] >= 3:
login_dic['count'] = 0
print("用户锁定!")
break
else:
print(f"账号或密码错误,剩余次数{3 - error_dic[username]}")
else:
login_dic['count'] = 0
print("请联系管理员!")
else:
print(f"账号或密码错误,剩余次数{login_dic['count']}")
error_dic[username] = error_dic.get(username, 0) + 1
if not error_dic:
error_dic = {username: 1}
f1.seek(0)
f1.write(json.dumps(error_dic))
f1.close()
def register():
"""
注册
:return:
"""
print("欢迎进入注册页面")
username = input("username:")
password = input("password:")
with open("userinfo", "r+", encoding="utf-8")as f1:
for i in f1:
file_username, file_password = i.strip().split(":")
if file_username == username:
print("用户名已存在")
break
else:
f1.write(f"{username}:{password}\n")
print("注册成功!")
@auth
def article():
"""
文章
:return:
"""
print(f"欢迎{login_dic['username']}登录文章")
@auth
def comment():
"""
评论
:return:
"""
print(f"欢迎{login_dic['username']}登录评论")
if os.path.getsize("comment_file"):
f = open("comment_file", "a+", encoding="utf-8")
content = input("期待你的神评论(Q/不评论):")
if content.upper() != "Q":
f.write(json.dumps({login_dic["username"]: content}, ensure_ascii=False) + '\n')
f.seek(0)
for i, em in enumerate(f, 1):
for k in json.loads(em):
print(f"{i}楼 - {k} : {json.loads(em)[k]}")
f.close()
else:
print("评论区没有内容!")
@auth
def log():
"""
日记
:return:
"""
print(f"欢迎{login_dic['username']}登录日记")
@auth
def collect():
"""
收藏
:return:
"""
print(f"欢迎{login_dic['username']}登录收藏")
@auth
def out():
"""
注销
:return:
"""
login_dic["flag"] = False
login_dic["username"] = None
print("注销成功!")
func_dic = {
"1": login,
"2": register,
"3": article,
"4": comment,
"5": log,
"6": collect,
"7": out,
"8": exit
}
while True:
choose = input(msg)
if choose in func_dic:
login_dic["count"] = 3
func_dic[choose]()
else:
print("请正确输入内容!")