OK much
This commit is contained in:
@@ -1,36 +1,48 @@
|
||||
from tinydb import TinyDB, Query
|
||||
import json
|
||||
|
||||
class UserList:
|
||||
def __init__(self, db_file='db/data/user/user_id_list.json'):
|
||||
"""初始化用户管理,自动打开并加载 JSON 数据文件。"""
|
||||
self.db_file = db_file
|
||||
self.db = TinyDB(self.db_file)
|
||||
self.user_query = Query()
|
||||
with open(self.db_file, 'r') as f:
|
||||
self.db = json.load(f)
|
||||
|
||||
def add_user(self, user_id, password):
|
||||
"""添加新的用户登录信息"""
|
||||
# 检查是否已经有该用户
|
||||
if not self.db.search(self.user_query.user_id == user_id):
|
||||
self.db.insert({'user_id': user_id, 'password': password})
|
||||
if user_id not in self.db:
|
||||
self.db[user_id] = password
|
||||
with open(self.db_file, 'w') as f:
|
||||
json.dump(self.db, f, indent=4)
|
||||
else:
|
||||
print(f"User with ID {user_id} already exists.")
|
||||
|
||||
def get_user(self, user_id):
|
||||
def has_user(self, user_id):
|
||||
"""检查用户是否存在"""
|
||||
return user_id in self.db
|
||||
|
||||
def get_user_pswd(self, user_id):
|
||||
"""获取指定 user_id 的用户信息"""
|
||||
result = self.db.search(self.user_query.user_id == user_id)
|
||||
return result[0] if result else None
|
||||
|
||||
if user_id in self.db:
|
||||
result = self.db[user_id]
|
||||
return result
|
||||
return None
|
||||
|
||||
def update_password(self, user_id, new_password):
|
||||
"""更新用户的密码"""
|
||||
self.db.update({'password': new_password}, self.user_query.user_id == user_id)
|
||||
assert self.db.get(user_id) is not None, f"User with ID {user_id} does not exist."
|
||||
self.db[user_id] = new_password
|
||||
with open(self.db_file, 'w') as f:
|
||||
json.dump(self.db, f, indent=4)
|
||||
|
||||
def delete_user(self, user_id):
|
||||
"""删除用户"""
|
||||
self.db.remove(self.user_query.user_id == user_id)
|
||||
|
||||
assert self.db.get(user_id) is not None, f"User with ID {user_id} does not exist."
|
||||
self.db.remove(user_id)
|
||||
|
||||
def get_all_users(self):
|
||||
"""获取所有用户的信息"""
|
||||
return self.db.all()
|
||||
return list(self.db.keys())
|
||||
|
||||
# 创建 UserList 实例
|
||||
# user_list = UserList()
|
||||
|
||||
Reference in New Issue
Block a user