lunduke-cli/config/configuration.py

71 lines
2.3 KiB
Python

import toml
from pathlib import Path
class Config:
"""Configuration class that loads settings from a TOML file"""
def __init__(self, config_file="config.toml"):
"""Initialize configuration from a TOML file
Args:
config_path (str): Path to the TOML configuration file
"""
config_dir = Path(__file__).resolve().parent
self.project_root = config_dir.parent
self.config_path = self.project_root / config_file
self._load_config()
def _load_config(self):
"""Load configuration from TOML file"""
if not self.config_path.exists():
raise FileNotFoundError(f"Configuration file not found: {self.config_path}")
# Load configuration
config_data = toml.load(self.config_path)
# Extract and set attributes
self.username = config_data["user"]["username"]
self.api_key_file = self.project_root.joinpath(
"keys", config_data["api"]["key_file"])
self.host = config_data["api"]["host"]
self._load_api_key()
def _load_api_key(self):
"""Load API key from the specified file"""
if not self.api_key_file.exists():
raise FileNotFoundError(f"API key file not found: {self.api_key_file}")
with (open(self.api_key_file, 'r') as key_file):
self.api_key = key_file.read().strip().replace('\n', '').replace('\r', '')
def get_headers(self):
"""Return headers for API requests"""
return {
"api_key": self.api_key,
"api_username": self.username
}
def get_api_url(self, endpoint=""):
"""Return the full API URL for the given endpoint
Args:
endpoint (str): The API endpoint (e.g., "posts.json")
Returns:
str: The full API URL
"""
# Handle cases where endpoint may already have leading slash
endpoint = endpoint.lstrip('/')
# Construct and return the full URL
return f"https://{self.host}/{endpoint}"
def __str__(self):
"""String representation of the configuration"""
return (f"Configuration:\n"
f"- Username: {self.username}\n"
f"- Host: {self.host}\n"
f"- API Key File: {self.api_key_file}\n"
f"- API Key: {'*' * 10}") # Don't show the actual key