🔍 Code Extractor

function clear_session

Maturity: 46

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.

File:
/tf/active/vicechatdev/docchat/blueprint.py
Lines:
288 - 310
Complexity:
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

  • flask
  • flask-login
  • uuid
  • pathlib
  • datetime
  • logging

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_clear_chat_session 85.8% similar

    Flask API endpoint that clears the chat history for a specific chat session identified by session_id.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_clear_history 84.7% similar

    Flask API endpoint that clears the chat history for the current user session by removing stored conversation data associated with the session ID.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_clear_memory 80.6% similar

    Flask API endpoint that clears the chat memory from the server-side chat engine, removing all stored conversation messages.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function clear_text_section_chat 73.8% similar

    Flask API endpoint that clears the chat history for a specific text section after verifying user ownership.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function clear_session_v1 73.8% similar

    Clears all messages from a chat session identified by session_id, resets the session's updated timestamp, and persists the changes to disk in a thread-safe manner.

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