function get_departments
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.
/tf/active/vicechatdev/CDocs/controllers/admin_controller.py
368 - 390
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
loggingtyping
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_department_name 67.8% similar
-
function get_department_code 66.1% similar
-
function get_system_settings 48.4% similar
-
function get_system_configuration 47.7% similar
-
function get_document_types 47.6% similar