import json class UserList: def __init__(self, db_file='db/data/user/user_id_list.json'): """初始化用户管理,自动打开并加载 JSON 数据文件。""" self.db_file = db_file with open(self.db_file, 'r', encoding='utf-8') as f: self.db = json.load(f) def add_user(self, user_id, password): """添加新的用户登录信息""" # 检查是否已经有该用户 if user_id not in self.db: self.db[user_id] = password with open(self.db_file, 'w', encoding='utf-8') as f: json.dump(self.db, f, indent=4) else: print(f"User with ID {user_id} already exists.") def has_user(self, user_id): """检查用户是否存在""" return user_id in self.db def get_user_pswd(self, user_id): """获取指定 user_id 的用户信息""" if user_id in self.db: result = self.db[user_id] return result return None def update_password(self, user_id, new_password): """更新用户的密码""" 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', encoding='utf-8') as f: json.dump(self.db, f, indent=4) def delete_user(self, 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 list(self.db.keys()) # 创建 UserList 实例 # user_list = UserList() # # 添加用户 # user_list.add_user("user123", "password123") # user_list.add_user("user456", "password456") # # 获取用户 # user = user_list.get_user("user123") # print(user) # # 更新密码 # user_list.update_password("user123", "newpassword") # # 获取所有用户 # all_users = user_list.get_all_users() # print(all_users) # # 删除用户 # user_list.delete_user("user123")