function clear_session
Flask route handler that clears the current user's chat session, deletes associated session data from memory and disk, and creates a new empty session.
/tf/active/vicechatdev/docchat/blueprint.py
288 - 310
moderate
Purpose
This endpoint allows users to reset their chat conversation history. It removes the existing session from the in-memory chat_sessions dictionary, deletes the corresponding session file from disk, and initializes a fresh session with a new UUID. This is useful when users want to start a new conversation context without the history of previous messages.
Source Code
def clear_session():
"""Clear current chat session"""
try:
session_id = session.get('chat_session_id')
if session_id and session_id in chat_sessions:
del chat_sessions[session_id]
session_file = SESSIONS_DIR / f"{session_id}.json"
if session_file.exists():
session_file.unlink()
# Create new session
session['chat_session_id'] = str(uuid_module.uuid4())
chat_sessions[session['chat_session_id']] = {
'messages': [],
'created_at': datetime.now(),
'updated_at': datetime.now(),
'user': get_current_username()
}
return jsonify({'success': True})
except Exception as e:
logger.error(f"Error clearing session: {e}")
return jsonify({'error': str(e)}), 500
Return Value
Returns a Flask JSON response. On success, returns {'success': True} with HTTP 200 status. On error, returns {'error': <error_message>} with HTTP 500 status. The response is a Flask Response object with application/json content type.
Dependencies
flaskflask-loginuuidpathlibdatetimelogging
Required Imports
from flask import Blueprint, jsonify, session
from flask_login import login_required
import uuid as uuid_module
from datetime import datetime
from pathlib import Path
import logging
Usage Example
# Client-side usage (JavaScript fetch):
fetch('/api/sessions/clear', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include'
})
.then(response => response.json())
.then(data => {
if (data.success) {
console.log('Session cleared successfully');
// Refresh chat UI or redirect
} else {
console.error('Error:', data.error);
}
});
# Server-side test usage:
with app.test_client() as client:
# Login first
client.post('/login', data={'username': 'test', 'password': 'pass'})
# Clear session
response = client.post('/api/sessions/clear')
assert response.json['success'] == True
Best Practices
- This function requires user authentication via @login_required decorator
- Ensure SESSIONS_DIR exists and has proper write permissions before calling this endpoint
- The function modifies global state (chat_sessions dictionary) - ensure thread safety in production with proper locking mechanisms
- Session files are deleted synchronously which could block the request - consider async deletion for large deployments
- Always handle the error response on the client side as session clearing can fail due to file system issues
- The new session is created immediately after clearing - ensure get_current_username() is available and returns valid data
- Consider implementing session cleanup background tasks to prevent orphaned session files
- The function uses Flask's session object which requires cookies to be enabled on the client side
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_clear_chat_session 85.8% similar
-
function api_clear_history 84.7% similar
-
function api_clear_memory 80.6% similar
-
function clear_text_section_chat 73.8% similar
-
function clear_session_v1 73.8% similar