class Config_v2
Configuration class that manages environment-based settings for a SharePoint to FileCloud synchronization application.
/tf/active/vicechatdev/SPFCsync/config.py
9 - 72
moderate
Purpose
This class serves as a centralized configuration manager for a SharePoint-to-FileCloud sync application. It loads configuration values from environment variables (via dotenv), provides validation for required settings, and sets up logging infrastructure. The class uses class-level attributes to store configuration values and provides class methods for validation and logging setup. It manages SharePoint authentication credentials, FileCloud connection details, sync behavior settings, and logging configuration.
Source Code
class Config:
"""Configuration class for SharePoint to FileCloud sync application."""
# SharePoint Configuration
SHAREPOINT_SITE_URL = os.getenv('SHAREPOINT_SITE_URL')
AZURE_CLIENT_ID = os.getenv('AZURE_CLIENT_ID')
AZURE_CLIENT_SECRET = os.getenv('AZURE_CLIENT_SECRET')
SHAREPOINT_DOCUMENTS_PATH = os.getenv('SHAREPOINT_DOCUMENTS_PATH', '/Shared Documents')
# FileCloud Configuration
FILECLOUD_SERVER_URL = os.getenv('FILECLOUD_SERVER_URL')
FILECLOUD_USERNAME = os.getenv('FILECLOUD_USERNAME')
FILECLOUD_PASSWORD = os.getenv('FILECLOUD_PASSWORD')
FILECLOUD_BASE_PATH = os.getenv('FILECLOUD_BASE_PATH', '/SHARED/SharePointSync')
# Sync Configuration
SYNC_INTERVAL_MINUTES = int(os.getenv('SYNC_INTERVAL_MINUTES', 30))
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
TIMEZONE = ZoneInfo(os.getenv('TIMEZONE', 'Europe/Brussels'))
SKIP_DIRECT_DOWNLOAD = os.getenv('SKIP_DIRECT_DOWNLOAD', 'false').lower() == 'true'
CREATE_EMPTY_FOLDERS = os.getenv('CREATE_EMPTY_FOLDERS', 'false').lower() == 'true'
DATE_COMPARISON_TOLERANCE_SECONDS = int(os.getenv('DATE_COMPARISON_TOLERANCE_SECONDS', 10))
# Logging Configuration
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOG_FILE = 'spfc_sync.log'
@classmethod
def validate_config(cls):
"""Validate that all required configuration values are set."""
required_configs = [
('SHAREPOINT_SITE_URL', cls.SHAREPOINT_SITE_URL),
('AZURE_CLIENT_ID', cls.AZURE_CLIENT_ID),
('AZURE_CLIENT_SECRET', cls.AZURE_CLIENT_SECRET),
('FILECLOUD_SERVER_URL', cls.FILECLOUD_SERVER_URL),
('FILECLOUD_USERNAME', cls.FILECLOUD_USERNAME),
('FILECLOUD_PASSWORD', cls.FILECLOUD_PASSWORD)
]
missing_configs = []
for config_name, config_value in required_configs:
if not config_value:
missing_configs.append(config_name)
if missing_configs:
raise ValueError(f"Missing required configuration: {', '.join(missing_configs)}")
return True
@classmethod
def setup_logging(cls):
"""Setup logging configuration."""
numeric_level = getattr(logging, cls.LOG_LEVEL.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError(f'Invalid log level: {cls.LOG_LEVEL}')
logging.basicConfig(
level=numeric_level,
format=cls.LOG_FORMAT,
handlers=[
logging.FileHandler(cls.LOG_FILE),
logging.StreamHandler()
]
)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
bases: This class does not take any __init__ parameters as it is designed to be used without instantiation. All configuration is accessed via class-level attributes and class methods.
Return Value
The class itself does not need to be instantiated. The validate_config() method returns True if all required configurations are present, otherwise raises ValueError. The setup_logging() method returns None but configures the global logging system as a side effect.
Class Interface
Methods
validate_config(cls) -> bool
Purpose: Validates that all required configuration values are set by checking for non-empty values in critical environment variables
Parameters:
cls: The class itself (classmethod parameter)
Returns: Returns True if all required configurations are present. Raises ValueError with a list of missing configurations if any are missing.
setup_logging(cls) -> None
Purpose: Configures the Python logging system with file and console handlers using the specified log level and format
Parameters:
cls: The class itself (classmethod parameter)
Returns: None. Configures the global logging system as a side effect. Raises ValueError if LOG_LEVEL is invalid.
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
SHAREPOINT_SITE_URL |
str | None | The URL of the SharePoint site to sync from (e.g., 'https://company.sharepoint.com/sites/sitename') | class |
AZURE_CLIENT_ID |
str | None | Azure AD application (client) ID for SharePoint authentication | class |
AZURE_CLIENT_SECRET |
str | None | Azure AD application client secret for SharePoint authentication | class |
SHAREPOINT_DOCUMENTS_PATH |
str | Path to the SharePoint documents library to sync (default: '/Shared Documents') | class |
FILECLOUD_SERVER_URL |
str | None | The base URL of the FileCloud server (e.g., 'https://filecloud.company.com') | class |
FILECLOUD_USERNAME |
str | None | Username for FileCloud authentication | class |
FILECLOUD_PASSWORD |
str | None | Password for FileCloud authentication | class |
FILECLOUD_BASE_PATH |
str | Base path in FileCloud where synced files will be stored (default: '/SHARED/SharePointSync') | class |
SYNC_INTERVAL_MINUTES |
int | Interval in minutes between sync operations (default: 30) | class |
LOG_LEVEL |
str | Logging level for the application (default: 'INFO', options: DEBUG, INFO, WARNING, ERROR, CRITICAL) | class |
TIMEZONE |
ZoneInfo | Timezone object for timestamp handling (default: Europe/Brussels) | class |
SKIP_DIRECT_DOWNLOAD |
bool | Whether to skip direct download attempts and use alternative methods (default: False) | class |
CREATE_EMPTY_FOLDERS |
bool | Whether to create empty folders during sync (default: False) | class |
DATE_COMPARISON_TOLERANCE_SECONDS |
int | Tolerance in seconds when comparing file modification dates to account for timestamp precision differences (default: 10) | class |
LOG_FORMAT |
str | Format string for log messages including timestamp, logger name, level, and message | class |
LOG_FILE |
str | Filename for the log file (default: 'spfc_sync.log') | class |
Dependencies
osdotenvloggingzoneinfo
Required Imports
import os
from dotenv import load_dotenv
import logging
from zoneinfo import ZoneInfo
Usage Example
# Load environment variables first
from dotenv import load_dotenv
load_dotenv()
# Import the Config class
from config import Config
# Validate configuration before use
try:
Config.validate_config()
print("Configuration is valid")
except ValueError as e:
print(f"Configuration error: {e}")
exit(1)
# Setup logging
Config.setup_logging()
# Access configuration values
sharepoint_url = Config.SHAREPOINT_SITE_URL
filecloud_url = Config.FILECLOUD_SERVER_URL
sync_interval = Config.SYNC_INTERVAL_MINUTES
timezone = Config.TIMEZONE
# Use configuration in your application
print(f"Syncing from {sharepoint_url} to {filecloud_url}")
print(f"Sync interval: {sync_interval} minutes")
print(f"Timezone: {timezone}")
Best Practices
- Always call Config.validate_config() before using the configuration to ensure all required values are present
- Call Config.setup_logging() early in your application lifecycle to configure logging properly
- Use load_dotenv() before importing or using the Config class to ensure environment variables are loaded
- Do not instantiate this class - it is designed to be used as a static configuration container
- Store sensitive credentials (client secrets, passwords) in environment variables or .env file, never hardcode them
- The class reads environment variables at import time, so changes to environment variables after import will not be reflected
- Boolean environment variables should be set to 'true' or 'false' (case-insensitive) for proper parsing
- Numeric environment variables (SYNC_INTERVAL_MINUTES, DATE_COMPARISON_TOLERANCE_SECONDS) must be valid integers
- The TIMEZONE value must be a valid IANA timezone identifier (e.g., 'Europe/Brussels', 'America/New_York')
- Log files are written to 'spfc_sync.log' in the current working directory by default
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class SharePointFileCloudSync 68.9% similar
-
class Config_v3 65.2% similar
-
function main_v33 65.1% similar
-
class SharePointClient 64.0% similar
-
function main_v10 62.8% similar