lunduke-cli/lunduke/client.py

70 lines
2.0 KiB
Python
Raw Normal View History

2025-04-11 21:46:02 +00:00
import requests
from requests import Response
from config.configuration import Config
2025-04-11 21:46:02 +00:00
from lunduke.config import DiscourseConfig
from lunduke.auth import DiscourseAuth
class DiscourseClient:
"""Main client for interacting with the Discourse API."""
def __init__(self, config_file="config.toml"):
2025-04-11 21:46:02 +00:00
"""
Initialize with just a config file path.
2025-04-11 21:46:02 +00:00
Args:
config_file: Path to configuration file (defaults to config.toml)
2025-04-11 21:46:02 +00:00
"""
# Load all configuration from a single file
config_data = Config(config_file)
# Create config and auth internally
self.config = DiscourseConfig(
host=config_data.host,
username=config_data.username
)
self.auth = DiscourseAuth(
api_key_file=config_data.api_key_file,
username=config_data.username
)
2025-04-11 21:46:02 +00:00
self.session = requests.Session()
def get(self, endpoint, params=None) -> Response:
2025-04-11 21:46:02 +00:00
"""
Make a GET request to the API.
Args:
endpoint: API endpoint (e.g., '/posts.json')
params: Optional query parameters
Returns:
Response data as JSON
"""
url = f"{self.config.get_base_url()}{endpoint}"
headers = self.auth.get_headers()
response = self.session.get(url, headers=headers, params=params)
response.raise_for_status() # Raise exception for error status codes
return response
2025-04-11 21:46:02 +00:00
def post(self, endpoint, data=None) -> Response:
2025-04-12 16:30:44 +00:00
"""
Make a POST request to the API.
Args:
endpoint: API endpoint (e.g., '/posts.json')
data: Data to be sent in the request body
Returns:
Response data as JSON
"""
url = f"{self.config.get_base_url()}{endpoint}"
headers = self.auth.get_headers()
response = self.session.post(url, headers=headers, json=data)
response.raise_for_status() # Raise exception for error status codes
return response