function smartstat_download_script
Flask route handler that downloads a generated Python analysis script for a specific SmartStat session by locating the most recent project directory and returning the analysis.py file.
/tf/active/vicechatdev/vice_ai/new_app.py
5424 - 5452
moderate
Purpose
This endpoint allows users to download the Python analysis script that was automatically generated during a SmartStat data analysis session. It searches for the most recent project directory within the session's folder structure and serves the analysis.py file as a downloadable attachment. This is useful for users who want to review, modify, or re-run the analysis code locally.
Source Code
def smartstat_download_script(session_id):
"""Download the generated Python analysis script"""
from pathlib import Path
from flask import send_file
try:
base_path = Path(smartstat_config.GENERATED_SCRIPTS_FOLDER) / session_id
# Find the most recent project directory
project_dirs = list(base_path.glob('project_*'))
if not project_dirs:
return jsonify({'error': 'No analysis script found'}), 404
latest_project = max(project_dirs, key=lambda p: p.stat().st_mtime)
script_path = latest_project / 'analysis.py'
if script_path.exists():
return send_file(
str(script_path),
as_attachment=True,
download_name=f'analysis_{session_id}.py',
mimetype='text/x-python'
)
else:
return jsonify({'error': 'Analysis script not found'}), 404
except Exception as e:
logger.error(f"Error downloading script: {e}")
return jsonify({'error': str(e)}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_id |
- | - | positional_or_keyword |
Parameter Details
session_id: Unique identifier for the SmartStat session. This is used to locate the correct session folder containing generated analysis scripts. Expected to be a string (typically UUID format) that corresponds to a valid session directory.
Return Value
Returns a Flask Response object. On success (200), sends the analysis.py file as a downloadable attachment with mimetype 'text/x-python' and filename 'analysis_{session_id}.py'. On error, returns a JSON response with an 'error' key and appropriate HTTP status code: 404 if no script is found, or 500 for other exceptions.
Dependencies
flaskpathlib
Required Imports
from pathlib import Path
from flask import send_file
from flask import jsonify
Conditional/Optional Imports
These imports are only needed under specific conditions:
from pathlib import Path
Condition: imported inside the function for file system operations
Required (conditional)from flask import send_file
Condition: imported inside the function for file download functionality
Required (conditional)Usage Example
# Example Flask app setup
from flask import Flask, jsonify, send_file
from pathlib import Path
import logging
app = Flask(__name__)
logger = logging.getLogger(__name__)
class smartstat_config:
GENERATED_SCRIPTS_FOLDER = '/path/to/generated/scripts'
def require_auth(f):
def wrapper(*args, **kwargs):
# Authentication logic here
return f(*args, **kwargs)
return wrapper
@app.route('/api/smartstat/<session_id>/download-script', methods=['GET'])
@require_auth
def smartstat_download_script(session_id):
from pathlib import Path
from flask import send_file
try:
base_path = Path(smartstat_config.GENERATED_SCRIPTS_FOLDER) / session_id
project_dirs = list(base_path.glob('project_*'))
if not project_dirs:
return jsonify({'error': 'No analysis script found'}), 404
latest_project = max(project_dirs, key=lambda p: p.stat().st_mtime)
script_path = latest_project / 'analysis.py'
if script_path.exists():
return send_file(
str(script_path),
as_attachment=True,
download_name=f'analysis_{session_id}.py',
mimetype='text/x-python'
)
else:
return jsonify({'error': 'Analysis script not found'}), 404
except Exception as e:
logger.error(f"Error downloading script: {e}")
return jsonify({'error': str(e)}), 500
# Client usage example:
# GET /api/smartstat/abc123-session-id/download-script
# Response: Downloads file 'analysis_abc123-session-id.py'
Best Practices
- Ensure the GENERATED_SCRIPTS_FOLDER path is properly configured and accessible
- The function uses modification time (st_mtime) to determine the most recent project directory, which assumes system clock accuracy
- Authentication is required via the require_auth decorator - ensure proper authentication is implemented
- Error handling returns appropriate HTTP status codes (404 for not found, 500 for server errors)
- The function converts Path objects to strings for send_file compatibility
- Session IDs should be validated to prevent directory traversal attacks
- Consider implementing rate limiting to prevent abuse of the download endpoint
- The glob pattern 'project_*' assumes a specific naming convention for project directories
- Logging is used for error tracking - ensure logger is properly configured
- The download_name parameter provides a user-friendly filename that includes the session_id
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function smartstat_download_log 81.8% similar
-
function download_generated_file 71.2% similar
-
function smartstat_get_plot 70.8% similar
-
function smartstat_upload_data 69.8% similar
-
function smartstat_save_to_document 69.5% similar