| import xml.etree.ElementTree as ET | |
| from pathlib import Path | |
| from typing import Optional, List | |
| class APIKeyManager: | |
| def __init__(self, config_path: str = "config/api_keys.xml"): | |
| self.config_path = Path(config_path) | |
| self._api_keys: List[str] = [] | |
| self._load_keys() | |
| def _load_keys(self): | |
| """Load API keys from XML file""" | |
| if not self.config_path.exists(): | |
| self._create_default_config() | |
| tree = ET.parse(self.config_path) | |
| root = tree.getroot() | |
| self._api_keys = [key.text for key in root.findall("key")] | |
| def _create_default_config(self): | |
| """Create default XML config file""" | |
| self.config_path.parent.mkdir(parents=True, exist_ok=True) | |
| root = ET.Element("api_keys") | |
| tree = ET.ElementTree(root) | |
| tree.write(self.config_path, encoding="utf-8", xml_declaration=True) | |
| def get_key(self, index: int = 0) -> Optional[str]: | |
| """Get API key by index""" | |
| try: | |
| return self._api_keys[index] | |
| except IndexError: | |
| return None | |
| def add_key(self, api_key: str): | |
| """Add new API key""" | |
| root = ET.parse(self.config_path).getroot() | |
| new_key = ET.SubElement(root, "key") | |
| new_key.text = api_key | |
| tree = ET.ElementTree(root) | |
| tree.write(self.config_path, encoding="utf-8", xml_declaration=True) | |
| self._api_keys.append(api_key) | |
| def remove_key(self, index: int): | |
| """Remove API key by index""" | |
| root = ET.parse(self.config_path).getroot() | |
| keys = root.findall("key") | |
| if 0 <= index < len(keys): | |
| root.remove(keys[index]) | |
| tree = ET.ElementTree(root) | |
| tree.write(self.config_path, encoding="utf-8", xml_declaration=True) | |
| self._api_keys.pop(index) | |
| def list_keys(self) -> List[str]: | |
| """List all API keys""" | |
| return self._api_keys.copy() | |