🔍 Code Extractor

function check_configuration_v1

Maturity: 45

Validates the presence of a .env configuration file and checks that all required environment variables (TENANT_ID, CLIENT_ID, CLIENT_SECRET, FROM_EMAIL) are defined.

File:
/tf/active/vicechatdev/email-forwarder/run_service.py
Lines:
35 - 52
Complexity:
simple

Purpose

This function performs configuration validation for an application that requires Azure/Microsoft authentication credentials and email settings. It checks for the existence of a .env file, loads environment variables from it, and verifies that all mandatory variables are present. Returns a tuple indicating success/failure status and a descriptive message. Commonly used during application startup or initialization to ensure proper configuration before attempting operations that depend on these credentials.

Source Code

def check_configuration():
    """Check if configuration file exists and has required variables."""
    if not Path('.env').exists():
        return False, "Configuration file .env not found"
    
    try:
        from dotenv import load_dotenv
        load_dotenv()
        
        required_vars = ['TENANT_ID', 'CLIENT_ID', 'CLIENT_SECRET', 'FROM_EMAIL']
        missing_vars = [var for var in required_vars if not os.getenv(var)]
        
        if missing_vars:
            return False, f"Missing required environment variables: {', '.join(missing_vars)}"
        
        return True, "Configuration is valid"
    except Exception as e:
        return False, f"Configuration error: {e}"

Return Value

Returns a tuple of (bool, str). The first element is True if configuration is valid (file exists and all required variables are present) or False if validation fails. The second element is a descriptive string message: 'Configuration is valid' on success, or an error message describing what went wrong (missing file, missing variables, or exception details) on failure.

Dependencies

  • python-dotenv
  • pathlib
  • os

Required Imports

import os
from pathlib import Path

Conditional/Optional Imports

These imports are only needed under specific conditions:

from dotenv import load_dotenv

Condition: imported inside the function after checking .env file exists, used to load environment variables from the .env file

Required (conditional)

Usage Example

# Ensure you have a .env file with required variables:
# TENANT_ID=your-tenant-id
# CLIENT_ID=your-client-id
# CLIENT_SECRET=your-client-secret
# FROM_EMAIL=your-email@example.com

import os
from pathlib import Path

def check_configuration():
    """Check if configuration file exists and has required variables."""
    if not Path('.env').exists():
        return False, "Configuration file .env not found"
    
    try:
        from dotenv import load_dotenv
        load_dotenv()
        
        required_vars = ['TENANT_ID', 'CLIENT_ID', 'CLIENT_SECRET', 'FROM_EMAIL']
        missing_vars = [var for var in required_vars if not os.getenv(var)]
        
        if missing_vars:
            return False, f"Missing required environment variables: {', '.join(missing_vars)}"
        
        return True, "Configuration is valid"
    except Exception as e:
        return False, f"Configuration error: {e}"

# Usage
is_valid, message = check_configuration()
if is_valid:
    print(f"Success: {message}")
    # Proceed with application logic
else:
    print(f"Error: {message}")
    # Handle configuration error

Best Practices

  • Call this function during application startup before attempting any operations that require the environment variables
  • Handle the returned tuple appropriately - check the boolean status before proceeding with application logic
  • Ensure the .env file is in the current working directory or adjust the Path check accordingly
  • Never commit the .env file to version control - add it to .gitignore
  • Consider logging the error messages for debugging purposes while avoiding exposure of sensitive credential values
  • The function uses lazy import of dotenv to avoid import errors if the file doesn't exist
  • All four environment variables (TENANT_ID, CLIENT_ID, CLIENT_SECRET, FROM_EMAIL) must be present and non-empty for validation to pass

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_configuration_v1 77.4% similar

    Validates that all required configuration variables (Azure AD credentials, OpenAI API key, and domain) are properly set and not using placeholder values.

    From: /tf/active/vicechatdev/find_email/test_vendor_extractor.py
  • function validate_config 72.1% similar

    Validates the presence of required Microsoft 365 configuration settings and raises an error if any are missing.

    From: /tf/active/vicechatdev/email-forwarder/src/config/settings.py
  • function main_v33 70.7% similar

    A validation function that checks SharePoint configuration settings from environment variables and provides diagnostic feedback on their validity.

    From: /tf/active/vicechatdev/SPFCsync/validate_config.py
  • function test_configuration_v3 67.3% similar

    A test function that validates the presence and loading of required Microsoft 365 and SMTP configuration settings from a settings module.

    From: /tf/active/vicechatdev/email-forwarder/test_imports.py
  • function validate_azure_client_secret 65.0% similar

    Validates an Azure client secret by checking for placeholder values, minimum length requirements, and common invalid patterns.

    From: /tf/active/vicechatdev/SPFCsync/validate_config.py
← Back to Browse