function create_admin_panel
Factory function that creates and returns a configured AdminPanel instance with optional template, session management, parent application reference, and embedding mode.
/tf/active/vicechatdev/CDocs/ui/admin_panel.py
1699 - 1731
moderate
Purpose
This factory function serves as the primary entry point for instantiating AdminPanel objects in the CDocs application. It provides a centralized way to create admin panels with consistent configuration, error handling, and logging. The function supports both standalone and embedded admin panel modes, allowing flexibility in how the admin interface is integrated into the application. It handles default template assignment and ensures proper error logging if panel creation fails.
Source Code
def create_admin_panel(template=None, session_manager=None, parent_app=None, embedded=False):
"""
Factory function to create an AdminPanel instance.
Args:
template: Panel template for the admin interface
session_manager: Session manager instance (optional)
parent_app: Reference to the parent application
embedded: Whether this is embedded in another panel
Returns:
AdminPanel: Configured admin panel instance
"""
try:
# Use the global admin template if none provided
if template is None:
template = admin_bp
# Create the admin panel instance
admin_panel = AdminPanel(
template=template,
session_manager=session_manager,
parent_app=parent_app,
embedded=embedded
)
logger.info("Admin panel created successfully")
return admin_panel
except Exception as e:
logger.error(f"Error creating admin panel: {e}")
logger.error(f"Traceback: {traceback.format_exc()}")
raise
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
template |
- | None | positional_or_keyword |
session_manager |
- | None | positional_or_keyword |
parent_app |
- | None | positional_or_keyword |
embedded |
- | False | positional_or_keyword |
Parameter Details
template: Panel template object for the admin interface UI. If None, defaults to the global 'admin_bp' template. Should be a Panel template instance (e.g., BootstrapTemplate) that defines the layout and styling of the admin panel.
session_manager: Optional SessionManager instance for handling user authentication and session state. If None, the AdminPanel may create its own or operate without session management. Used to track logged-in users and their permissions.
parent_app: Reference to the parent application object that contains this admin panel. Used for communication between the admin panel and the main application, allowing the panel to access application-level resources and trigger parent app methods.
embedded: Boolean flag indicating whether the admin panel is embedded within another panel (True) or runs as a standalone interface (False). Affects layout and navigation behavior. Default is False.
Return Value
Returns an AdminPanel instance that is fully configured with the provided parameters. The AdminPanel object provides administrative functionality including user management, system statistics, document management, and other admin operations. If an exception occurs during creation, the function raises the exception after logging the error details.
Dependencies
loggingtracebacktypingdatetimejsonpanelparampandasnumpymatplotlibhashlibuuid
Required Imports
import logging
import traceback
import panel as pn
from panel.template import BootstrapTemplate
from CDocs.config import settings
from CDocs.config import permissions
from CDocs.models.user_extensions import DocUser
from CDocs.controllers.admin_controller import get_system_stats, get_users, create_user, update_user, delete_user, get_departments, get_user_activity, get_document_stats
from CDocs.controllers import ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError
from CDocs.auth.session_manager import SessionManager
from CDocs.utils.notifications import NotificationManager
from CDocs.db.db_operations import run_query
Conditional/Optional Imports
These imports are only needed under specific conditions:
import pandas as pd
Condition: Required if AdminPanel uses Tabulator widgets or DataFrame displays for user/document data
Required (conditional)import numpy as np
Condition: Required if AdminPanel performs numerical computations on statistics or analytics
Required (conditional)import matplotlib.pyplot as plt
Condition: Required if AdminPanel generates charts or visualizations for system statistics
Required (conditional)import hashlib
Condition: Required if AdminPanel handles password hashing or security operations
Required (conditional)import uuid
Condition: Required if AdminPanel generates unique identifiers for users or resources
Required (conditional)Usage Example
import logging
from panel.template import BootstrapTemplate
from CDocs.auth.session_manager import SessionManager
# Setup logging
logger = logging.getLogger(__name__)
# Create a session manager
session_mgr = SessionManager()
# Create admin panel with default template
admin_panel = create_admin_panel(
session_manager=session_mgr
)
# Create embedded admin panel with custom template
custom_template = BootstrapTemplate(title='Custom Admin')
embedded_panel = create_admin_panel(
template=custom_template,
session_manager=session_mgr,
parent_app=my_app,
embedded=True
)
# Serve the admin panel
admin_panel.servable()
Best Practices
- Always wrap calls to this function in try-except blocks to handle potential AdminPanel instantiation errors
- Provide a session_manager when authentication and user tracking are required
- Use the embedded=True flag when integrating the admin panel into a larger application to ensure proper layout behavior
- Ensure the global 'admin_bp' template is properly initialized before calling this function without a template parameter
- Monitor logs for 'Admin panel created successfully' messages to verify successful creation
- Pass parent_app reference when the admin panel needs to communicate with or access resources from the main application
- Consider creating a singleton pattern wrapper if only one admin panel instance should exist in the application
- Ensure all CDocs dependencies (models, controllers, auth modules) are properly configured before creating the admin panel
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_embedded_admin_panel 84.5% similar
-
function get_admin_view 71.6% similar
-
function create_approval_panel 71.0% similar
-
function create_approval_panel_v1 69.3% similar
-
function create_training_dashboard 64.9% similar