🔍 Code Extractor

function admin_cleanup

Maturity: 46

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

File:
/tf/active/vicechatdev/full_smartstat/app.py
Lines:
1617 - 1637
Complexity:
simple

Purpose

This endpoint allows administrators to manually initiate cleanup operations that remove old analysis sessions from the system. It accepts an optional parameter to specify how old sessions must be before deletion, defaulting to a configured value. The function is designed for administrative maintenance tasks to prevent database bloat and manage storage resources.

Source Code

def admin_cleanup():
    """Admin endpoint to manually trigger cleanup"""
    try:
        data = request.get_json() or {}
        days_old = data.get('days_old', app_config.CLEANUP_OLD_SESSIONS_DAYS)
        
        # Clean up old sessions
        cleanup_count = analysis_service.cleanup_old_sessions(days_old=days_old)
        
        return jsonify({
            'success': True,
            'message': f'Cleanup completed: {cleanup_count} old sessions removed',
            'sessions_cleaned': cleanup_count
        })
        
    except Exception as e:
        logger.error(f"Error in admin cleanup: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

Return Value

Returns a Flask JSON response. On success: returns a dictionary with 'success': True, 'message' describing the cleanup result, and 'sessions_cleaned' containing the count of removed sessions (HTTP 200). On error: returns a dictionary with 'success': False and 'error' containing the error message (HTTP 500).

Dependencies

  • flask
  • logging

Required Imports

from flask import Flask
from flask import request
from flask import jsonify
import logging

Usage Example

# Example using curl or requests library
import requests

# Trigger cleanup with default days threshold
response = requests.post('http://localhost:5000/admin/cleanup')
print(response.json())
# Output: {'success': True, 'message': 'Cleanup completed: 5 old sessions removed', 'sessions_cleaned': 5}

# Trigger cleanup with custom days threshold
response = requests.post(
    'http://localhost:5000/admin/cleanup',
    json={'days_old': 30}
)
print(response.json())
# Output: {'success': True, 'message': 'Cleanup completed: 10 old sessions removed', 'sessions_cleaned': 10}

Best Practices

  • This endpoint should be protected with authentication/authorization middleware to prevent unauthorized access
  • Consider implementing rate limiting to prevent abuse of the cleanup operation
  • The cleanup operation may be resource-intensive; consider running it during off-peak hours
  • Monitor the sessions_cleaned count to understand cleanup patterns and adjust CLEANUP_OLD_SESSIONS_DAYS if needed
  • Ensure the analysis_service.cleanup_old_sessions method is transactional to prevent partial cleanups
  • Consider adding request validation to ensure days_old is a positive integer
  • Log cleanup operations for audit trails and monitoring purposes
  • Test the endpoint in a staging environment before using in production to understand performance impact

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function admin_cleanup_orphaned 83.7% 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
  • function delete_session 73.7% similar

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

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function get_analysis_progress 69.6% similar

    Flask route handler that retrieves the progress status of a running analysis task and performs cleanup of completed/failed analyses after a timeout period.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function admin_status 68.3% similar

    Flask route handler that retrieves comprehensive system status information including disk usage, session counts, analysis counts, and orphaned file detection for an admin dashboard.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function clear_session 62.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