🔍 Code Extractor

function get_admin_view

Maturity: 50

Retrieves an admin panel view component for a Panel-based application, handling user authentication and error cases gracefully.

File:
/tf/active/vicechatdev/CDocs/ui/admin_panel.py
Lines:
1761 - 1790
Complexity:
moderate

Purpose

This function serves as a factory method to create and configure an embedded admin panel view for a Panel (HoloViz) web application. It handles user authentication by accepting either a direct user object or extracting it from the parent application, creates the admin panel through the create_embedded_admin_panel function, and returns the configured view. If any errors occur during creation, it returns a user-friendly error display instead of crashing.

Source Code

def get_admin_view(parent_app=None, user=None):
    """
    Get the admin panel view directly without creating a full template.
    
    Args:
        parent_app: Reference to the parent application
        user: Current user (optional, will be set from parent_app if available)
        
    Returns:
        Panel view component
    """
    try:
        admin_panel = create_embedded_admin_panel(parent_app=parent_app)
        
        # Set user if provided
        if user:
            admin_panel.set_user(user)
        elif parent_app and hasattr(parent_app, 'current_user'):
            admin_panel.set_user(parent_app.current_user)
            
        return admin_panel.get_admin_view()
        
    except Exception as e:
        logger.error(f"Error getting admin view: {e}")
        # Return error message instead of raising
        return pn.Column(
            pn.pane.Markdown("# Admin Panel Error"),
            pn.pane.Markdown(f"**Error:** {str(e)}"),
            pn.pane.Markdown("Please check the logs for more details.")
        )

Parameters

Name Type Default Kind
parent_app - None positional_or_keyword
user - None positional_or_keyword

Parameter Details

parent_app: Reference to the parent Panel application object. Used to access application-level properties like current_user. Can be None if user is provided directly. Expected to have a 'current_user' attribute if user parameter is not provided.

user: Optional user object (likely DocUser instance) representing the currently authenticated user. If None, the function attempts to retrieve the user from parent_app.current_user. Used to set permissions and personalize the admin panel view.

Return Value

Returns a Panel view component (likely a pn.Column or similar Panel layout object) containing the admin panel interface. In case of errors, returns a pn.Column with error messages displayed as Markdown panes, ensuring the application doesn't crash and provides user feedback.

Dependencies

  • panel
  • logging
  • CDocs.config
  • CDocs.models.user_extensions
  • CDocs.controllers.admin_controller
  • CDocs.auth.session_manager
  • CDocs.utils.notifications
  • CDocs.db.db_operations
  • pandas
  • numpy
  • matplotlib
  • typing

Required Imports

import panel as pn
import logging
from CDocs.models.user_extensions import DocUser
from CDocs.config import settings
from CDocs.config import permissions

Conditional/Optional Imports

These imports are only needed under specific conditions:

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

Condition: Required by create_embedded_admin_panel function which is called internally

Required (conditional)
from CDocs.db.db_operations import run_query

Condition: Required by admin controller functions for database operations

Required (conditional)
from CDocs.auth.session_manager import SessionManager

Condition: Required for user session management in admin panel

Required (conditional)
from CDocs.utils.notifications import NotificationManager

Condition: Required for displaying notifications in admin panel

Required (conditional)

Usage Example

import panel as pn
from CDocs.models.user_extensions import DocUser
from your_module import get_admin_view

# Initialize Panel
pn.extension()

# Example 1: With parent app and user from app
class MyApp:
    def __init__(self):
        self.current_user = DocUser(username='admin', role='admin')

app = MyApp()
admin_view = get_admin_view(parent_app=app)

# Example 2: With explicit user
user = DocUser(username='admin', role='admin')
admin_view = get_admin_view(user=user)

# Example 3: Serve the admin view
admin_view.servable()

# Example 4: Embed in a template
template = pn.template.FastListTemplate(
    title='Admin Dashboard',
    main=[admin_view]
)
template.servable()

Best Practices

  • Always ensure Panel is initialized with pn.extension() before calling this function
  • Provide either parent_app with current_user attribute or user parameter for proper authentication
  • The function handles errors gracefully, but ensure logger is properly configured to capture error details
  • The returned component can be directly added to Panel templates or served standalone
  • Ensure the create_embedded_admin_panel function is available in the module scope
  • User object should be an instance of DocUser with appropriate permissions for admin access
  • Consider wrapping this in a try-except block if you need custom error handling beyond the built-in error display
  • The function returns a Panel component, so it should be used within a Panel application context

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_embedded_admin_panel 75.1% similar

    Creates and returns an embedded AdminPanel instance configured for integration within other application interfaces without its own template or session manager.

    From: /tf/active/vicechatdev/CDocs/ui/admin_panel.py
  • function create_admin_panel 71.6% similar

    Factory function that creates and returns a configured AdminPanel instance with optional template, session management, parent application reference, and embedding mode.

    From: /tf/active/vicechatdev/CDocs/ui/admin_panel.py
  • function create_approval_panel 57.0% similar

    Factory function that creates and initializes an ApprovalPanel instance with error handling, supporting both standalone and embedded modes for document approval management.

    From: /tf/active/vicechatdev/CDocs/ui/approval_panel_bis.py
  • function create_approval_panel_v1 56.5% similar

    Factory function that creates and initializes an ApprovalPanel instance for managing document approvals, with error handling and fallback to a minimal panel on failure.

    From: /tf/active/vicechatdev/CDocs/ui/approval_panel.py
  • function create_document_detail 52.7% similar

    Factory function that creates and initializes a DocumentDetail panel component, optionally loading a specific document by its UID.

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