function get_or_create_session
Retrieves an existing chat session by ID or creates a new one if it doesn't exist, with thread-safe access and persistent storage support.
/tf/active/vicechatdev/docchat/app.py
223 - 240
moderate
Purpose
This function manages chat session lifecycle in a web application. It provides thread-safe access to chat sessions stored in memory, attempts to load sessions from disk if not in memory, and creates new sessions with default structure if they don't exist. It's designed for multi-user chat applications where session persistence and concurrent access are important.
Source Code
def get_or_create_session(session_id):
"""Get or create a chat session"""
with session_lock:
if session_id not in chat_sessions:
# Try loading from disk first
session_data = load_session_from_disk(session_id)
if session_data:
chat_sessions[session_id] = session_data
else:
# Create new session
chat_sessions[session_id] = {
'messages': [],
'created_at': datetime.now(),
'updated_at': datetime.now(),
'settings': {} # Store user settings
}
save_session_to_disk(session_id)
return chat_sessions[session_id]
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_id |
- | - | positional_or_keyword |
Parameter Details
session_id: Unique identifier for the chat session. Expected to be a string (likely UUID or similar). Used as a key to retrieve or create session data from the in-memory dictionary and disk storage.
Return Value
Returns a dictionary representing the chat session with the following structure: {'messages': list of chat messages, 'created_at': datetime object of session creation, 'updated_at': datetime object of last update, 'settings': dictionary for user-specific settings}. The returned dictionary is a reference to the session stored in the global chat_sessions dictionary.
Dependencies
datetimethreading
Required Imports
from datetime import datetime
from threading import Lock
Usage Example
from datetime import datetime
from threading import Lock
# Required global setup
session_lock = Lock()
chat_sessions = {}
def load_session_from_disk(session_id):
# Implementation to load from disk
return None
def save_session_to_disk(session_id):
# Implementation to save to disk
pass
# Usage
session_id = 'user-123-session'
session_data = get_or_create_session(session_id)
# Access session data
print(session_data['messages'])
print(session_data['created_at'])
# Add a message to the session
session_data['messages'].append({'role': 'user', 'content': 'Hello'})
session_data['updated_at'] = datetime.now()
Best Practices
- Always use this function to access chat sessions rather than directly accessing the chat_sessions dictionary to ensure thread safety
- The function uses a lock to prevent race conditions in multi-threaded environments, so avoid holding references to the lock elsewhere
- Ensure load_session_from_disk and save_session_to_disk are properly implemented before using this function
- The returned dictionary is mutable and shared across all callers, so modifications will affect the global state
- Consider implementing session expiration logic to prevent unbounded memory growth
- The function creates sessions with empty settings; populate these as needed for your application
- Remember to call save_session_to_disk after modifying session data to persist changes
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_chat_session 78.7% similar
-
function get_chat_session 77.5% similar
-
function add_message_to_session 73.7% similar
-
function clear_session_v1 72.5% similar
-
function save_chat_session_to_file 67.7% similar