Fix: Remove misuse of asyncio.to_thread with async context manager in remove_user.py

This commit is contained in:
Whispering Wind
2025-05-02 13:26:57 +03:30
committed by GitHub
parent 8ba46b9878
commit 2008156e20

View File

@ -7,42 +7,30 @@ import asyncio
from init_paths import * from init_paths import *
from paths import * from paths import *
async def remove_user(username): def sync_remove_user(username):
"""
Remove a user from the USERS_FILE asynchronously.
Args:
username (str): The username to remove
Returns:
int: 0 on success, 1 on failure
"""
if not os.path.isfile(USERS_FILE): if not os.path.isfile(USERS_FILE):
print(f"Error: Config file {USERS_FILE} not found.") return 1, f"Error: Config file {USERS_FILE} not found."
return 1
try: try:
async with asyncio.to_thread(open, USERS_FILE, 'r') as f: with open(USERS_FILE, 'r') as f:
try: try:
users_data = json.load(f) users_data = json.load(f)
except json.JSONDecodeError: except json.JSONDecodeError:
print(f"Error: {USERS_FILE} contains invalid JSON.") return 1, f"Error: {USERS_FILE} contains invalid JSON."
return 1
if username in users_data: if username in users_data:
del users_data[username] del users_data[username]
async with asyncio.to_thread(open, USERS_FILE, 'w') as f: with open(USERS_FILE, 'w') as f:
json.dump(users_data, f, indent=4) json.dump(users_data, f, indent=4)
print(f"User {username} removed successfully.") return 0, f"User {username} removed successfully."
else: else:
print(f"Error: User {username} not found.") return 1, f"Error: User {username} not found."
return 1
except Exception as e: except Exception as e:
print(f"Error: {str(e)}") return 1, f"Error: {str(e)}"
return 1
return 0 async def remove_user(username):
return await asyncio.to_thread(sync_remove_user, username)
async def main(): async def main():
if len(sys.argv) != 2: if len(sys.argv) != 2:
@ -50,7 +38,8 @@ async def main():
sys.exit(1) sys.exit(1)
username = sys.argv[1] username = sys.argv[1]
exit_code = await remove_user(username) exit_code, message = await remove_user(username)
print(message)
sys.exit(exit_code) sys.exit(exit_code)
if __name__ == "__main__": if __name__ == "__main__":