class SessionManager
A session management class for Panel applications that provides user authentication and arbitrary key-value storage using Panel's built-in state management system.
/tf/active/vicechatdev/CDocs/auth/session_manager.py
13 - 108
simple
Purpose
SessionManager provides a clean interface for managing user sessions in Panel web applications. It handles user authentication state, stores user IDs, and provides generic key-value storage for session data. The class wraps Panel's pn.state.cache to ensure consistent session management across the application lifecycle. It's designed for web applications that need to track user authentication status and maintain session-specific data.
Source Code
class SessionManager:
"""
Session manager for Panel applications
Uses Panel's built-in state management to store user session information
"""
def __init__(self):
"""Initialize the session manager"""
# Ensure Panel state is initialized
if not hasattr(pn.state, 'cache'):
pn.state.cache = {}
def set_user_id(self, user_id):
"""
Set the current user ID in the session
Args:
user_id: The user ID to store
Returns:
bool: True if successful, False otherwise
"""
if not user_id:
return False
# Store in Panel's state
pn.state.cache['user_id'] = user_id
logger.debug(f"User ID set in session: {user_id}")
return True
def get_user_id(self):
"""
Get the current user ID from the session
Returns:
The user ID or None if not set
"""
return pn.state.cache.get('user_id')
def clear_session(self):
"""Clear the current session"""
if 'user_id' in pn.state.cache:
del pn.state.cache['user_id']
logger.debug("Session cleared")
def is_authenticated(self):
"""
Check if the current session is authenticated
Returns:
bool: True if authenticated, False otherwise
"""
return self.get_user_id() is not None
def store_value(self, key, value):
"""
Store an arbitrary value in the session
Args:
key (str): The key to store the value under
value: The value to store
Returns:
bool: True if successful
"""
pn.state.cache[key] = value
return True
def get_value(self, key, default=None):
"""
Retrieve a value from the session
Args:
key (str): The key to retrieve
default: The default value if the key doesn't exist
Returns:
The stored value or the default
"""
return pn.state.cache.get(key, default)
def remove_value(self, key):
"""
Remove a value from the session
Args:
key (str): The key to remove
Returns:
bool: True if the key existed and was removed, False otherwise
"""
if key in pn.state.cache:
del pn.state.cache[key]
return True
return False
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
__init__: No parameters required. The constructor initializes the Panel state cache if it doesn't already exist, ensuring the session storage backend is ready for use.
Return Value
Instantiation returns a SessionManager object. Methods return: set_user_id() returns bool (True on success, False if user_id is empty); get_user_id() returns the stored user ID or None; clear_session() returns None; is_authenticated() returns bool; store_value() returns bool (True on success); get_value() returns the stored value or default; remove_value() returns bool (True if key existed and was removed, False otherwise).
Class Interface
Methods
__init__(self)
Purpose: Initialize the session manager and ensure Panel state cache exists
Returns: None
set_user_id(self, user_id) -> bool
Purpose: Store the current user ID in the session for authentication tracking
Parameters:
user_id: The user identifier to store in the session. Can be string, int, or any hashable type. Must be truthy (not None, empty string, 0, etc.)
Returns: bool: True if the user_id was successfully stored, False if user_id was empty/falsy
get_user_id(self)
Purpose: Retrieve the current user ID from the session
Returns: The stored user ID (any type) or None if no user ID has been set
clear_session(self)
Purpose: Remove the user ID from the session, effectively logging out the user
Returns: None
is_authenticated(self) -> bool
Purpose: Check whether a user is currently authenticated by verifying if a user ID exists in the session
Returns: bool: True if a user_id is set in the session, False otherwise
store_value(self, key, value) -> bool
Purpose: Store an arbitrary key-value pair in the session cache for custom session data
Parameters:
key: str: The key under which to store the value. Should be a string identifiervalue: Any serializable value to store in the session. Can be any Python object that Panel's state can handle
Returns: bool: Always returns True to indicate successful storage
get_value(self, key, default=None)
Purpose: Retrieve a value from the session cache by key, with optional default fallback
Parameters:
key: str: The key to look up in the session cachedefault: Optional value to return if the key doesn't exist in the session. Defaults to None
Returns: The stored value associated with the key, or the default value if the key is not found
remove_value(self, key) -> bool
Purpose: Remove a specific key-value pair from the session cache
Parameters:
key: str: The key to remove from the session cache
Returns: bool: True if the key existed and was successfully removed, False if the key was not found
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
pn.state.cache |
dict | Panel's built-in session cache dictionary used as the underlying storage mechanism. Accessed but not stored as an instance attribute. Contains all session data including 'user_id' and any custom key-value pairs | instance |
Dependencies
panellogging
Required Imports
import panel as pn
import logging
Usage Example
import panel as pn
import logging
# Setup logger
logger = logging.getLogger(__name__)
# Initialize Panel
pn.extension()
# Create session manager
session_mgr = SessionManager()
# Set user ID for authentication
session_mgr.set_user_id('user123')
# Check authentication status
if session_mgr.is_authenticated():
user_id = session_mgr.get_user_id()
print(f'Authenticated as: {user_id}')
# Store arbitrary session data
session_mgr.store_value('theme', 'dark')
session_mgr.store_value('preferences', {'lang': 'en', 'notifications': True})
# Retrieve session data
theme = session_mgr.get_value('theme', default='light')
prefs = session_mgr.get_value('preferences')
# Remove specific value
session_mgr.remove_value('theme')
# Clear entire session
session_mgr.clear_session()
Best Practices
- Always check is_authenticated() before accessing user-specific resources
- Call clear_session() when users log out to prevent data leakage
- The class relies on Panel's pn.state.cache which is session-specific in Panel applications
- Ensure Panel is properly initialized before instantiating SessionManager
- Use store_value() and get_value() for custom session data beyond user authentication
- The logger variable must be defined in the module scope for debug logging to work
- Session data persists only for the duration of the Panel session and is not shared across browser tabs or sessions
- set_user_id() validates that user_id is not empty/None before storing
- Use get_value() with a default parameter to avoid None checks in calling code
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class _state 72.8% similar
-
function _initialize_session_info 64.3% similar
-
class User 60.8% similar
-
class SmartStatSession 58.0% similar
-
class ControlledDocApp 57.0% similar