20250911-初步功能已完成
This commit is contained in:
@@ -3,7 +3,8 @@ import json
|
||||
from pathlib import Path
|
||||
|
||||
from Utils.LogManager import LogManager
|
||||
|
||||
from pathlib import Path
|
||||
import portalocker as locker # ① 引入跨平台锁
|
||||
|
||||
class JsonUtils:
|
||||
@staticmethod
|
||||
@@ -190,39 +191,33 @@ class JsonUtils:
|
||||
data = cls._read_json_list(file_path)
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def delete_json_items(cls, match: dict, filename="log/last_message.json", multi: bool = True) -> int:
|
||||
"""
|
||||
删除 JSON 文件(数组)中符合条件的项
|
||||
:param match: 匹配条件(如 {"sender": "xxx"})
|
||||
:param filename: JSON 文件路径
|
||||
:param multi: True=删除所有匹配项,False=只删除第一项
|
||||
:return: 删除的条数
|
||||
"""
|
||||
def delete_json_items(cls,
|
||||
match: dict,
|
||||
filename: str = "log/last_message.json",
|
||||
multi: bool = True) -> int:
|
||||
file_path = Path(filename)
|
||||
data = cls._read_json_list(file_path)
|
||||
with file_path.open('r+', encoding='utf-8') as f:
|
||||
locker.lock(f, locker.LOCK_EX) # ② 加独占锁(Windows/Linux 通用)
|
||||
try:
|
||||
data = json.load(f)
|
||||
if not isinstance(match, dict):
|
||||
return 0
|
||||
|
||||
if not isinstance(match, dict):
|
||||
return 0
|
||||
deleted = 0
|
||||
new_data = []
|
||||
for item in data:
|
||||
if isinstance(item, dict) and all(item.get(k) == v for k, v in match.items()):
|
||||
if multi or deleted == 0: # 删多条 / 第一条
|
||||
deleted += 1
|
||||
continue
|
||||
new_data.append(item)
|
||||
|
||||
deleted = 0
|
||||
new_data = []
|
||||
for item in data:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
# 是否匹配
|
||||
if all(item.get(k) == v for k, v in match.items()):
|
||||
deleted += 1
|
||||
if not multi and deleted > 0:
|
||||
# 只删除一条 → 剩下的全保留
|
||||
new_data.extend(data[data.index(item) + 1:])
|
||||
break
|
||||
continue
|
||||
new_data.append(item)
|
||||
if deleted:
|
||||
f.seek(0)
|
||||
json.dump(new_data, f, ensure_ascii=False, indent=2)
|
||||
f.truncate()
|
||||
|
||||
if deleted > 0:
|
||||
cls._write_json_list(file_path, new_data)
|
||||
|
||||
return deleted
|
||||
return deleted
|
||||
finally:
|
||||
locker.unlock(f) # ③ 解锁
|
||||
Reference in New Issue
Block a user