function save_data_section_analysis
Flask API endpoint that saves analysis results (plots, conclusions, and analysis data) from a data analysis session to a data section in the database.
/tf/active/vicechatdev/vice_ai/new_app.py
4584 - 4634
moderate
Purpose
This endpoint retrieves analysis results from an active data analysis session and persists them to the corresponding data section. It verifies user ownership, checks for an active analysis session, collects generated plots and conclusions, and updates the data section with all analysis artifacts. This allows users to save their data analysis work for later reference or inclusion in documents.
Source Code
def save_data_section_analysis(section_id):
"""Save analysis results to data section"""
if not DATA_ANALYSIS_AVAILABLE:
return jsonify({'error': 'Data analysis service not available'}), 503
user_email = get_current_user()
# Verify ownership
data_section = data_section_service.get_data_section(section_id)
if not data_section or data_section.owner != user_email:
return jsonify({'error': 'Data section not found or access denied'}), 404
if not data_section.analysis_session_id:
return jsonify({'error': 'No analysis session found'}), 400
try:
# Get session data
session = data_analysis_service.get_analysis_session(data_section.analysis_session_id)
if not session:
return jsonify({'error': 'Session not found'}), 404
# Collect all generated plots
plots = []
if session.generated_plots:
plots = json.loads(session.generated_plots) if isinstance(session.generated_plots, str) else session.generated_plots
# Get analysis conclusions
conclusions = session.analysis_conclusions or ''
# Update data section with results using service methods
if plots:
data_section_service.update_plots(section_id, plots)
if conclusions:
data_section_service.update_conclusions(section_id, conclusions)
# Save any analysis results to current_content
if hasattr(session, 'last_result'):
data_section_refresh = data_section_service.get_data_section(section_id)
data_section_refresh.analysis_results = session.last_result
data_section_service.update_data_section(data_section_refresh)
return jsonify({
'success': True,
'message': 'Analysis results saved to data section',
'plots_count': len(plots)
})
except Exception as e:
logger.error(f"Error saving analysis results: {e}")
return jsonify({'error': str(e)}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
section_id |
- | - | positional_or_keyword |
Parameter Details
section_id: String identifier for the data section where analysis results should be saved. Must correspond to an existing DataSection owned by the authenticated user.
Return Value
Returns a Flask JSON response. On success (200): {'success': True, 'message': 'Analysis results saved to data section', 'plots_count': <number>}. On error: 503 if data analysis service unavailable, 404 if section not found or access denied or session not found, 400 if no analysis session exists, 500 for other exceptions with error message.
Dependencies
flaskjsonlogging
Required Imports
from flask import jsonify
import json
import logging
Usage Example
# Client-side usage (JavaScript fetch example)
fetch('/api/data-sections/abc123/analysis/save', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
console.log(`Saved ${data.plots_count} plots`);
} else {
console.error(data.error);
}
});
# Server-side test example
with app.test_client() as client:
response = client.post(
'/api/data-sections/section123/analysis/save',
headers={'Authorization': 'Bearer token'}
)
result = response.get_json()
assert result['success'] == True
Best Practices
- Always verify user authentication and ownership before allowing access to data sections
- Check DATA_ANALYSIS_AVAILABLE flag before attempting to use analysis services
- Handle JSON parsing carefully as generated_plots may be stored as string or object
- Refresh data section from database after updates to ensure consistency
- Use service layer methods (update_plots, update_conclusions) rather than direct database access
- Log errors with sufficient context for debugging
- Return appropriate HTTP status codes (503 for service unavailable, 404 for not found, 400 for bad request, 500 for server errors)
- Validate that analysis_session_id exists before attempting to retrieve session data
- Use try-except blocks to catch and handle exceptions gracefully
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_data_section_analysis_session 82.7% similar
-
function smartstat_save_to_document 76.3% similar
-
function update_data_section_conclusions 75.5% similar
-
function export_analysis_content 75.4% similar
-
function update_analysis_conclusions 75.1% similar