implement toml config

This commit is contained in:
Greg Gauthier 2025-04-12 18:16:27 +01:00
parent 4ed17de9ae
commit 03a65a2244
6 changed files with 111 additions and 5 deletions

2
.gitignore vendored
View File

@ -3,3 +3,5 @@
.idea/ .idea/
keys/ keys/
poetry.lock poetry.lock
config.toml
**/*.ipynb

0
config/__init__.py Normal file
View File

71
config/configuration.py Normal file
View File

@ -0,0 +1,71 @@
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
"""
self.project_root = Path(__file__).resolve().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"]
# Load API key
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()
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

28
config/create_config.py Normal file
View File

@ -0,0 +1,28 @@
import os
import toml
def create_sample_config(config_path="config.toml"):
"""Create a sample configuration file if it doesn't exist"""
if os.path.exists(config_path):
print(f"Configuration file already exists: {config_path}")
return
config_data = {
"user": {
"username": "joe_doakes"
},
"api": {
"key_file": "../keys/cli_key.txt",
"host": "discourse.forum.com"
}
}
with open(config_path, "w") as config_file:
toml.dump(config_data, config_file)
print(f"Created sample configuration file: {config_path}")
# Create a sample configuration file
create_sample_config()

View File

@ -1,19 +1,23 @@
from config.configuration import Config
from lunduke.config import DiscourseConfig from lunduke.config import DiscourseConfig
from lunduke.auth import DiscourseAuth from lunduke.auth import DiscourseAuth
from lunduke.client import DiscourseClient from lunduke.client import DiscourseClient
def main(): def main():
config_data = Config()
print(config_data)
# Set up configuration # Set up configuration
config = DiscourseConfig( config = DiscourseConfig(
host='forum.lunduke.com', host=config_data.host,
username='gmgauthier' username=config_data.username
) )
# Set up authentication # Set up authentication
auth = DiscourseAuth( auth = DiscourseAuth(
api_key_file='../keys/cli_key.txt', api_key_file=config_data.api_key_file,
username=config.username username=config_data.username
) )
# Create client # Create client

View File

@ -8,7 +8,8 @@ authors = [
readme = "README.md" readme = "README.md"
requires-python = ">=3.12" requires-python = ">=3.12"
dependencies = [ dependencies = [
"requests (>=2.32.3,<3.0.0)" "requests (>=2.32.3,<3.0.0)",
"toml (>=0.10.2, <1.0.0)"
] ]