🔍 Code Extractor

function get_departments

Maturity: 48

Retrieves all departments from application settings and formats them as a list of dictionaries with standardized department information including id, code, name, description, and active status.

File:
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
Lines:
368 - 390
Complexity:
simple

Purpose

This function serves as a data access layer to fetch department information from the application's settings configuration. It transforms the settings.DEPARTMENTS dictionary into a standardized list format suitable for API responses, UI rendering, or other components that need department data. The function includes error handling to return an empty list if the settings are unavailable or malformed, and logs any errors encountered during retrieval.

Source Code

def get_departments() -> List[Dict[str, Any]]:
    """
    Get all departments from settings.
    
    Returns:
        List of dictionaries with department information
    """
    departments = []
    
    try:
        for name, code in settings.DEPARTMENTS.items():
            departments.append({
                'id': code,
                'code': code, 
                'name': name,
                'description': f'{name} Department',
                'active': True
            })
            
        return departments
    except Exception as e:
        logger.error(f"Error getting departments: {e}")
        return []

Return Value

Type: List[Dict[str, Any]]

Returns a List[Dict[str, Any]] where each dictionary represents a department with the following keys: 'id' (department code), 'code' (department code), 'name' (department name from settings), 'description' (formatted string '{name} Department'), and 'active' (boolean, always True). Returns an empty list if an exception occurs during retrieval.

Dependencies

  • logging
  • typing

Required Imports

import logging
from typing import List, Dict, Any
from CDocs.config import settings

Usage Example

# Assuming settings.DEPARTMENTS = {'Engineering': 'ENG', 'Sales': 'SAL', 'HR': 'HR'}
# and logger is configured

from typing import List, Dict, Any
from CDocs.config import settings
import logging

logger = logging.getLogger(__name__)

def get_departments() -> List[Dict[str, Any]]:
    departments = []
    try:
        for name, code in settings.DEPARTMENTS.items():
            departments.append({
                'id': code,
                'code': code, 
                'name': name,
                'description': f'{name} Department',
                'active': True
            })
        return departments
    except Exception as e:
        logger.error(f"Error getting departments: {e}")
        return []

# Usage
departments = get_departments()
for dept in departments:
    print(f"{dept['name']} ({dept['code']}): {dept['description']}")

# Output:
# Engineering (ENG): Engineering Department
# Sales (SAL): Sales Department
# HR (HR): HR Department

Best Practices

  • Ensure settings.DEPARTMENTS is properly configured before calling this function
  • The function returns an empty list on error rather than raising exceptions, so check the logs if unexpected empty results occur
  • The 'logger' variable must be defined in the module scope before this function is called
  • Both 'id' and 'code' fields contain the same value (department code) for redundancy/compatibility
  • All departments are marked as 'active': True by default; implement additional logic if inactive departments need to be supported
  • Consider caching the results if this function is called frequently, as it iterates through settings each time

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_department_name 67.8% similar

    Looks up and returns the full department name corresponding to a given department code by searching through a DEPARTMENTS dictionary.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function get_department_code 66.1% similar

    Retrieves a department code by looking up a department's full name in a DEPARTMENTS dictionary, returning the original name if not found.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function get_system_settings 48.4% similar

    Retrieves system-wide configuration settings from a Neo4j database, returning default values if settings are not found or an error occurs.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function get_system_configuration 47.7% similar

    Retrieves system configuration settings from environment variables for display in an admin panel, including database connections, authentication settings, and operational parameters.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function get_document_types 47.6% similar

    Retrieves document type configurations from application settings, optionally filtering by a specific type code, and returns them as a list of dictionaries with detailed metadata.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
← Back to Browse