function format_session_args
Converts session arguments dictionary with byte keys/values to a formatted JSON string for readable logging.
/tf/active/vicechatdev/CDocs/main.py
169 - 209
simple
Purpose
This utility function is designed to format Panel (pn.state) session arguments for logging purposes. It handles the conversion of byte-encoded keys and values to UTF-8 strings, making session data human-readable. The function is particularly useful for debugging web applications built with Panel framework where session arguments are often stored as bytes. It gracefully handles decoding errors and provides formatted JSON output with proper indentation.
Source Code
def format_session_args(session_args):
"""
Format session args for readable logging (converts byte keys/values to strings).
Args:
session_args: The session_args dictionary from pn.state
Returns:
str: A formatted string representation of session args
"""
if not session_args:
return "None"
try:
# Create a new dict with decoded keys and values
formatted_args = {}
for key, values in session_args.items():
# Decode key from bytes to string
if isinstance(key, bytes):
str_key = key.decode('utf-8')
else:
str_key = str(key)
# Handle list of values - typically each value is a bytes object
str_values = []
for val in values:
if isinstance(val, bytes):
# Try to decode, fall back to repr if it fails
try:
str_values.append(val.decode('utf-8'))
except UnicodeDecodeError:
str_values.append(repr(val))
else:
str_values.append(str(val))
formatted_args[str_key] = str_values
return json.dumps(formatted_args, indent=2)
except Exception as e:
return f"Error formatting session args: {str(e)}"
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_args |
- | - | positional_or_keyword |
Parameter Details
session_args: A dictionary containing session arguments from pn.state. Expected structure is a dictionary where keys can be bytes or strings, and values are lists containing bytes or string objects. Can be None or empty. Typically contains URL parameters or session state data passed to a Panel application.
Return Value
Returns a string representation of the session arguments. If session_args is None or empty, returns 'None'. On success, returns a JSON-formatted string with 2-space indentation containing the decoded session arguments with string keys mapping to lists of string values. If any exception occurs during formatting, returns an error message string in the format 'Error formatting session args: {error_message}'.
Dependencies
json
Required Imports
import json
Usage Example
import json
# Example 1: Basic usage with byte keys and values
session_args = {
b'user_id': [b'12345'],
b'token': [b'abc123xyz'],
'page': ['dashboard']
}
formatted = format_session_args(session_args)
print(formatted)
# Output:
# {
# "user_id": ["12345"],
# "token": ["abc123xyz"],
# "page": ["dashboard"]
# }
# Example 2: Empty or None session args
formatted_none = format_session_args(None)
print(formatted_none) # Output: None
formatted_empty = format_session_args({})
print(formatted_empty) # Output: None
# Example 3: With Panel application
import panel as pn
def my_app():
session_args = pn.state.session_args
formatted_args = format_session_args(session_args)
print(f"Session arguments: {formatted_args}")
return pn.pane.Markdown(f"\n{formatted_args}\n")
Best Practices
- Always check if session_args is None or empty before processing to avoid unnecessary operations
- The function handles UnicodeDecodeError gracefully by falling back to repr() for non-UTF-8 decodable bytes
- Use this function for logging and debugging only, not for production data processing where you need strict type guarantees
- The function wraps all operations in a try-except block, so it will never raise an exception - always returns a string
- When using with Panel applications, call this function with pn.state.session_args to format URL parameters and session data
- The returned JSON string is indented with 2 spaces for readability in logs
- Be aware that sensitive data in session_args will be exposed in the formatted output - avoid logging sensitive information
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function save_session_to_disk 48.2% similar
-
class SessionManager 47.8% similar
-
function save_session_to_disk_v1 47.6% similar
-
function _initialize_session_info 45.9% similar
-
function load_session_from_disk 45.8% similar