🔍 Code Extractor

function export_report

Maturity: 50

Flask route handler that exports an analysis report for a given session in either PDF or Word format, retrieving session data and generating a downloadable file.

File:
/tf/active/vicechatdev/full_smartstat/app.py
Lines:
1466 - 1484
Complexity:
moderate

Purpose

This function serves as a web endpoint to export analysis reports. It validates the requested format (PDF or Word), retrieves the session summary from the analysis service, generates a report file using the session data, and returns it as a downloadable attachment. It's designed to provide users with formatted reports of their statistical analysis sessions.

Source Code

def export_report(session_id, format_type):
    """Export analysis report"""
    try:
        if format_type not in ['pdf', 'word']:
            return jsonify({'error': 'Invalid format'}), 400
        
        # Get session summary
        summary = analysis_service.get_session_summary(session_id)
        if not summary['success']:
            return jsonify({'error': 'Session not found'}), 404
        
        # Generate report (placeholder - implement report generator)
        report_path = generate_report(session_id, summary, format_type)
        
        return send_file(report_path, as_attachment=True)
        
    except Exception as e:
        logger.error(f"Error exporting report: {str(e)}")
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword
format_type - - positional_or_keyword

Parameter Details

session_id: String identifier for the analysis session. Used to retrieve the session summary and associated analysis data. Must correspond to an existing session in the analysis service.

format_type: String specifying the desired export format. Must be either 'pdf' or 'word'. Any other value will result in a 400 error response.

Return Value

Returns a Flask Response object. On success, returns a file download response (send_file) with the generated report as an attachment. On error, returns a JSON response with an 'error' key and appropriate HTTP status code: 400 for invalid format, 404 for session not found, or 500 for other exceptions.

Dependencies

  • flask
  • logging
  • pathlib
  • os
  • json
  • uuid
  • datetime
  • typing
  • tempfile
  • base64
  • pandas
  • threading
  • time
  • werkzeug
  • config
  • models
  • services
  • script_executor
  • data_processor
  • dynamic_schema_discovery
  • statistical_agent
  • enhanced_sql_workflow
  • manual_relationships
  • shutil

Required Imports

from flask import Flask
from flask import jsonify
from flask import send_file
import logging
from services import StatisticalAnalysisService

Usage Example

# Assuming Flask app is set up with proper configuration
# Client-side request example:
import requests

session_id = 'abc123-session-id'
format_type = 'pdf'  # or 'word'

response = requests.get(f'http://localhost:5000/export/{session_id}/{format_type}')

if response.status_code == 200:
    with open(f'report.{format_type}', 'wb') as f:
        f.write(response.content)
    print('Report downloaded successfully')
else:
    error = response.json().get('error')
    print(f'Error: {error}')

Best Practices

  • The generate_report function is marked as a placeholder and must be implemented before this endpoint is fully functional
  • Ensure proper cleanup of temporary report files after sending to prevent disk space issues
  • Consider implementing rate limiting to prevent abuse of report generation
  • Add authentication/authorization checks to ensure users can only export their own session reports
  • Validate session_id format to prevent injection attacks
  • Consider adding support for additional export formats by extending the format_type validation
  • Implement proper logging for audit trails of report exports
  • The report_path returned by generate_report should be a valid file path accessible by the Flask application
  • Consider implementing asynchronous report generation for large reports to avoid request timeouts
  • Add Content-Disposition headers with meaningful filenames for better user experience

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function export_analysis_content 76.2% similar

    Flask API endpoint that exports analysis session content for integration into documents, with authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function export_to_pdf_v1 73.6% similar

    Flask route handler that exports a chat conversation to a PDF file with formatted messages, roles, and references using the reportlab library.

    From: /tf/active/vicechatdev/docchat/app.py
  • function download_file 71.9% similar

    Flask route handler that serves generated report files for download from a designated reports folder.

    From: /tf/active/vicechatdev/leexi/app.py
  • function export_document 71.7% similar

    Flask route handler that exports a document in either DOCX or PDF format, verifying user ownership and document access before generating the export file.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_results 71.1% similar

    Flask route handler that retrieves and returns comprehensive analysis results for a given session, including summary data, generated files, interpretations, and execution tracking information.

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