🔍 Code Extractor

function clear_text_section_chat

Maturity: 46

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

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
876 - 895
Complexity:
simple

Purpose

This endpoint provides a secure way to delete all chat messages associated with a text section. It authenticates the user, verifies they own the text section, and then clears the chat history through the text_section_service. This is useful for resetting conversations or removing sensitive chat data while preserving the text section itself.

Source Code

def clear_text_section_chat(section_id):
    """Clear chat history for a text section"""
    user_email = get_current_user()
    
    # Verify ownership
    text_section = text_section_service.get_text_section(section_id)
    if not text_section or text_section.owner != user_email:
        return jsonify({'error': 'Text section not found or access denied'}), 404
    
    try:
        success = text_section_service.clear_chat_history(section_id)
        
        if success:
            return jsonify({'success': True})
        else:
            return jsonify({'error': 'Failed to clear chat history'}), 500
            
    except Exception as e:
        logger.error(f"Error clearing chat: {e}")
        return jsonify({'error': str(e)}), 400

Parameters

Name Type Default Kind
section_id - - positional_or_keyword

Parameter Details

section_id: String identifier (likely UUID) of the text section whose chat history should be cleared. This is extracted from the URL path parameter. Must correspond to an existing text section owned by the authenticated user.

Return Value

Returns a Flask JSON response tuple. On success: ({'success': True}, 200). On failure: ({'error': 'error message'}, status_code) where status_code is 404 for not found/access denied, 500 for service failure, or 400 for exceptions.

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import logging

Usage Example

# Client-side usage (JavaScript fetch example):
// DELETE request to clear chat history
fetch('/api/text-sections/abc-123-def-456/chat', {
  method: 'DELETE',
  headers: {
    'Authorization': 'Bearer <token>',
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  if (data.success) {
    console.log('Chat history cleared successfully');
  } else {
    console.error('Error:', data.error);
  }
})
.catch(error => console.error('Request failed:', error));

Best Practices

  • Always verify user ownership before allowing deletion operations to prevent unauthorized access
  • Use proper HTTP status codes: 404 for not found/unauthorized, 500 for server errors, 400 for bad requests
  • Log errors with sufficient context for debugging while avoiding sensitive data exposure
  • Return consistent JSON response structure for both success and error cases
  • The function relies on external services (text_section_service) - ensure these are properly initialized before route registration
  • Consider implementing rate limiting for delete operations to prevent abuse
  • The require_auth decorator must be properly configured to handle authentication failures
  • Ensure get_current_user() returns a valid user email or raises appropriate exceptions

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_section_chat_history 83.2% similar

    Flask API endpoint that retrieves chat history for a specific text section, verifying user ownership before returning messages.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function delete_text_section 80.9% similar

    Flask API endpoint that deletes a text section after verifying user ownership and authentication.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_clear_history 77.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_chat_session 75.7% 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 clear_session 73.8% similar

    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.

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