🔍 Code Extractor

function delete_session

Maturity: 46

Flask route handler that deletes an analysis session and all its associated data from the database, returning a JSON response indicating success or failure.

File:
/tf/active/vicechatdev/full_smartstat/app.py
Lines:
1422 - 1447
Complexity:
simple

Purpose

This endpoint provides a RESTful DELETE operation to remove analysis sessions from the system. It retrieves session information, attempts deletion through the analysis service, and returns appropriate HTTP status codes (200 for success, 404 for not found, 500 for errors). This is typically used when users want to clean up old analysis sessions or remove unwanted data.

Source Code

def delete_session(session_id):
    """Delete analysis session and all associated data"""
    try:
        # Get session info before deletion for cleanup
        summary = analysis_service.get_session_summary(session_id)
        
        # Delete session data from database
        success = analysis_service.delete_session(session_id)
        
        if success:
            return jsonify({
                'success': True,
                'message': f'Session {session_id} deleted successfully'
            })
        else:
            return jsonify({
                'success': False,
                'error': 'Session not found or could not be deleted'
            }), 404
        
    except Exception as e:
        logger.error(f"Error deleting session: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword

Parameter Details

session_id: String identifier for the analysis session to be deleted. This is extracted from the URL path parameter and should be a valid session ID that exists in the database. The format depends on how sessions are created (likely UUID or similar unique identifier).

Return Value

Returns a Flask Response object containing JSON data. On success (200): {'success': True, 'message': 'Session {session_id} deleted successfully'}. On not found (404): {'success': False, 'error': 'Session not found or could not be deleted'}. On error (500): {'success': False, 'error': '<error message>'}. The response includes appropriate HTTP status codes.

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import logging

Usage Example

# Client-side usage example (using requests library)
import requests

session_id = 'abc123-session-id'
response = requests.delete(f'http://localhost:5000/delete_session/{session_id}')

if response.status_code == 200:
    data = response.json()
    if data['success']:
        print(f"Session deleted: {data['message']}")
    else:
        print(f"Deletion failed: {data['error']}")
elif response.status_code == 404:
    print("Session not found")
else:
    print(f"Error: {response.json()['error']}")

# Server-side integration example
# Assuming Flask app setup:
from flask import Flask, jsonify
import logging

app = Flask(__name__)
logger = logging.getLogger(__name__)

# analysis_service must be initialized
# from services import StatisticalAnalysisService
# analysis_service = StatisticalAnalysisService()

@app.route('/delete_session/<session_id>', methods=['DELETE'])
def delete_session(session_id):
    # Function implementation here
    pass

Best Practices

  • Always check the success field in the JSON response before assuming the operation completed successfully
  • Handle all three possible HTTP status codes (200, 404, 500) in client code
  • The function retrieves session summary before deletion but doesn't use it - this may be for logging or future cleanup operations
  • Ensure proper authentication/authorization is implemented before this endpoint in production to prevent unauthorized session deletion
  • Consider implementing soft deletes instead of hard deletes for audit trail purposes
  • The analysis_service.delete_session() method should handle cascading deletion of all associated data
  • Log the session_id in error messages for debugging purposes
  • Consider adding rate limiting to prevent abuse of the delete endpoint

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_analysis_session 77.0% similar

    Flask API endpoint that retrieves details of a specific data analysis session for an authenticated user, ensuring the user has access to the requested session.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_session_status 75.0% similar

    Flask API endpoint that retrieves the current status and summary of an analysis session by its ID.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function create_new_session 73.9% similar

    Flask route handler that creates a new analysis session with an optional title and description, returning a unique session ID.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function admin_cleanup 73.7% similar

    Flask route handler that provides an admin endpoint to manually trigger cleanup of old analysis sessions based on a configurable age threshold.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function admin_cleanup_orphaned 73.4% similar

    Flask route handler that cleans up orphaned files and directories from deleted analysis sessions by calling the analysis service's cleanup method and returning detailed results.

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