function api_export_document
Flask API endpoint that exports a document in either DOCX or PDF format, with authentication and authorization checks.
/tf/active/vicechatdev/vice_ai/complex_app.py
1265 - 1303
moderate
Purpose
This endpoint allows authenticated users to export their own documents in specified formats (DOCX or PDF). It validates document ownership, checks format availability, generates the export file using format-specific converters, and returns the file as a downloadable attachment. It includes comprehensive error handling for missing documents, access denial, unsupported formats, and unavailable export services.
Source Code
def api_export_document(doc_id, format):
"""Export document in specified format"""
try:
document = get_document(doc_id)
if not document:
return jsonify({'error': 'Document not found'}), 404
if document.author != get_user_id():
return jsonify({'error': 'Access denied'}), 403
if format not in ['docx', 'pdf']:
return jsonify({'error': 'Unsupported format'}), 400
if format == 'docx' and not DOCX_AVAILABLE:
return jsonify({'error': 'DOCX export not available'}), 500
if format == 'pdf' and not PDF_AVAILABLE:
return jsonify({'error': 'PDF export not available'}), 500
# Generate the export file
if format == 'docx':
file_data = export_to_docx(document)
filename = f"{document.title}.docx"
mimetype = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
else: # PDF
file_data = export_to_pdf(document)
filename = f"{document.title}.pdf"
mimetype = 'application/pdf'
return send_file(
BytesIO(file_data),
as_attachment=True,
download_name=filename,
mimetype=mimetype
)
except Exception as e:
logger.error(f"Export document error: {e}")
return jsonify({'error': 'Failed to export document'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
doc_id |
- | - | positional_or_keyword |
format |
- | - | positional_or_keyword |
Parameter Details
doc_id: String identifier for the document to be exported. Used to retrieve the document from the database/storage. Must correspond to an existing document.
format: String specifying the export format. Must be either 'docx' or 'pdf'. Any other value will result in a 400 error response.
Return Value
Returns a Flask Response object. On success (200), returns a file download response with the exported document as an attachment with appropriate MIME type. On error, returns a JSON object with an 'error' key and appropriate HTTP status code: 404 (document not found), 403 (access denied), 400 (unsupported format), 500 (export unavailable or internal error).
Dependencies
flaskpython-docxreportlablogging
Required Imports
from flask import jsonify
from flask import send_file
from io import BytesIO
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from docx import Document
Condition: Required when DOCX_AVAILABLE is True and format='docx' is requested
Required (conditional)from reportlab.lib.pagesizes import letter, A4
Condition: Required when PDF_AVAILABLE is True and format='pdf' is requested
Required (conditional)from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
Condition: Required when PDF_AVAILABLE is True and format='pdf' is requested
Required (conditional)Usage Example
# Example HTTP request to the endpoint:
# GET /api/documents/abc123/export/pdf
# Headers: Authorization: Bearer <token>
# Example response (success):
# Status: 200
# Content-Type: application/pdf
# Content-Disposition: attachment; filename="My Document.pdf"
# Body: <binary PDF data>
# Example response (error):
# Status: 404
# Content-Type: application/json
# Body: {"error": "Document not found"}
# To call this endpoint from Python:
import requests
response = requests.get(
'http://localhost:5000/api/documents/abc123/export/pdf',
headers={'Authorization': 'Bearer your_token_here'}
)
if response.status_code == 200:
with open('exported_document.pdf', 'wb') as f:
f.write(response.content)
else:
print(f"Error: {response.json()['error']}")
Best Practices
- Always ensure the require_auth decorator is properly implemented to prevent unauthorized access
- Verify that DOCX_AVAILABLE and PDF_AVAILABLE flags are set correctly based on installed dependencies
- Implement proper error logging to track export failures
- Sanitize document.title before using it as filename to prevent path traversal attacks
- Consider implementing rate limiting to prevent abuse of export functionality
- Ensure export_to_docx() and export_to_pdf() functions handle large documents efficiently
- The function checks document ownership (document.author != get_user_id()) - ensure this authorization logic matches your security requirements
- Consider adding file size limits for exports to prevent memory issues
- The BytesIO object should be properly managed; Flask's send_file handles cleanup automatically
- Consider caching exported files for frequently accessed documents to improve performance
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function export_document 90.2% similar
-
function api_upload_document_v1 72.5% similar
-
function api_upload_document 69.0% similar
-
function api_get_document 68.4% similar
-
function api_create_document 68.4% similar