To set up your server configuration in a clean and modular way, while ensuring it integrates well with your existing Config class for LLM configurations and API key management, and your separate logger, you can follow the structure below. This approach will keep your server configuration isolated, reusable, and easy to maintain, without mixing in API key or logging concerns.
Here’s how you can adapt and improve your ServerConfig setup:
Step 1: Define the ServerConfig Data Class
Use Python's @dataclass to define the ServerConfig with default values and a method to load from environment variables. This is similar to what you already have, but I'll streamline it and ensure it aligns with your requirements.
from dataclasses import dataclass
import os
from typing import Optional
@dataclass
class ServerConfig:
"""Server configuration"""
host: str = "localhost"
port: int = 8000
log_level: str = "INFO"
health_check_interval: int = 60
max_connections: int = 100
debug: bool = False
@classmethod
def from_env(cls) -> 'ServerConfig':
"""Load configuration from environment variables with defaults."""
return cls(
host=os.getenv("SERVER_HOST", cls.host),
port=int(os.getenv("SERVER_PORT", str(cls.port))),
log_level=os.getenv("LOG_LEVEL", cls.log_level),
health_check_interval=int(os.getenv("HEALTH_CHECK_INTERVAL", str(cls.health_check_interval))),
max_connections=int(os.getenv("MAX_CONNECTIONS", str(cls.max_connections))),
debug=os.getenv("DEBUG", "false").lower() == "true"
)
Step 2: Update the Config Class
Your Config class should handle loading environment variables (e.g., from a .env file) and provide a method to retrieve the ServerConfig. Since you already have a separate configuration for LLM and API keys, and a logger, the Config class here will focus solely on server-related settings.
from pathlib import Path
from typing import Optional
from dotenv import load_dotenv
class Config:
def __init__(self, config_file: Optional[str] = None):
self.config_file = config_file or ".env"
self.load_environment()
def load_environment(self) -> None:
"""Load environment variables from the specified config file."""
if Path(self.config_file).exists():
load_dotenv(self.config_file)
else:
print(f"Warning: Config file '{self.config_file}' not found. Using default environment variables.")
def get_server_config(self) -> ServerConfig:
"""Get server configuration from environment variables."""
return ServerConfig.from_env()
Step 3: Example Usage in Your Application
Here’s how you can use the Config and ServerConfig in your application. This assumes you have a .env file for environment variables and that your server setup (e.g., using asyncio, aiohttp, or another framework) will use these configurations.
Example .env File
Create a .env file in your project root to override default values:
SERVER_HOST=0.0.0.0
SERVER_PORT=8080
LOG_LEVEL=DEBUG
HEALTH_CHECK_INTERVAL=30
MAX_CONNECTIONS=200
DEBUG=true
Example Application Code
Here’s an example of how you might integrate this into your server application:
from config import Config, ServerConfig # Assuming your Config and ServerConfig are in a 'config.py' file
def start_server(config: ServerConfig):
print(f"Starting server on {config.host}:{config.port}")
print(f"Log Level: {config.log_level}")
print(f"Health Check Interval: {config.health_check_interval} seconds")
print(f"Max Connections: {config.max_connections}")
print(f"Debug Mode: {config.debug}")
# Add your server startup logic here (e.g., using aiohttp, FastAPI, etc.)
if __name__ == "__main__":
# Initialize the Config class, which loads environment variables
config_manager = Config(config_file=".env")
# Get the server configuration
server_config = config_manager.get_server_config()
# Start the server with the configuration
start_server(server_config)
Step 4: Integration with Existing LLM Config and Logger
Since you mentioned you already have a separate configuration for LLM and API keys, and a logger, you don’t need to include those in the ServerConfig. Instead, you can keep them modular. For example:
- LLM Configuration: Managed by a separate class (e.g.,
LLMConfig) in your existing Config class or another module.
- Logger: Initialized separately, possibly using the
log_level from ServerConfig if needed, but otherwise independent.
Here’s an example of how you might integrate the logger with the ServerConfig:
import logging
def setup_logger(log_level: str) -> None:
"""Set up the logger with the specified log level."""
logging.basicConfig(
level=getattr(logging, log_level.upper(), logging.INFO),
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
if __name__ == "__main__":
config_manager = Config(config_file=".env")
server_config = config_manager.get_server_config()
# Set up the logger using the log level from ServerConfig
setup_logger(server_config.log_level)
# Start the server
start_server(server_config)
Step 5: Benefits of This Approach
- Modularity: The
ServerConfig is isolated and focused solely on server-related settings, making it easy to maintain and extend.
- Environment Variable Support: Environment variables are loaded seamlessly, with defaults as a fallback, using the
.env file.
- Type Safety: Using
@dataclass ensures type hints and reduces runtime errors.
- Separation of Concerns: API keys, LLM configurations, and logging are kept separate, adhering to good software design principles.
- Flexibility: You can easily add more server-related settings to
ServerConfig without affecting other parts of your application.
Step 6: Testing the Configuration
To test your setup, you can create a simple script or use a testing framework like pytest. Here’s an example test:
import os
from config import Config, ServerConfig
def test_server_config_defaults():
config_manager = Config(config_file="nonexistent.env") # Ensure no .env file is loaded
server_config = config_manager.get_server_config()
assert server_config.host == "localhost"
assert server_config.port == 8000
assert server_config.log_level == "INFO"
assert server_config.health_check_interval == 60
assert server_config.max_connections == 100
assert server_config.debug is False
def test_server_config_from_env():
# Set environment variables for testing
os.environ["SERVER_HOST"] = "0.0.0.0"
os.environ["SERVER_PORT"] = "8080"
os.environ["LOG_LEVEL"] = "DEBUG"
os.environ["HEALTH_CHECK_INTERVAL"] = "30"
os.environ["MAX_CONNECTIONS"] = "200"
os.environ["DEBUG"] = "true"
config_manager = Config(config_file="nonexistent.env") # Ensure no .env file is loaded
server_config = config_manager.get_server_config()
assert server_config.host == "0.0.0.0"
assert server_config.port == 8080
assert server_config.log_level == "DEBUG"
assert server_config.health_check_interval == 30
assert server_config.max_connections == 200
assert server_config.debug is True
Run the tests using pytest to ensure your configuration works as expected.
Final Notes
- Ensure you have the
python-dotenv package installed (pip install python-dotenv) to load .env files.
- Keep your
.env file secure and out of version control (e.g., add it to .gitignore).
- If you need to add more server-related settings in the future, simply extend the
ServerConfig class and update the from_env method accordingly.
This setup should meet your needs while keeping your codebase clean, modular, and easy to maintain.