function api_remove_document
Flask API endpoint that removes an uploaded document from the session and deletes its associated file from the filesystem.
/tf/active/vicechatdev/vice_ai/new_app.py
2421 - 2448
moderate
Purpose
This endpoint handles DELETE requests to remove documents that users have uploaded. It cleans up both the physical file from the temporary directory and the document metadata from the user's session. It includes error handling for file system operations and returns appropriate HTTP status codes.
Source Code
def api_remove_document(document_id):
"""Remove an uploaded document"""
try:
if 'uploaded_documents' in session and document_id in session['uploaded_documents']:
doc_info = session['uploaded_documents'][document_id]
# Clean up file
try:
file_path = doc_info.get('file_path')
if file_path and os.path.exists(file_path):
os.remove(file_path)
# Try to remove the temp directory if empty
temp_dir = os.path.dirname(file_path)
if os.path.exists(temp_dir):
os.rmdir(temp_dir)
except Exception as e:
logger.warning(f"Could not clean up file: {e}")
# Remove from session
del session['uploaded_documents'][document_id]
return jsonify({'message': 'Document removed successfully'})
else:
return jsonify({'error': 'Document not found'}), 404
except Exception as e:
logger.error(f"Remove document error: {e}")
return jsonify({'error': 'Failed to remove document'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
document_id |
- | - | positional_or_keyword |
Parameter Details
document_id: String identifier for the document to be removed. This ID is used as a key to look up the document in the session's 'uploaded_documents' dictionary. The ID should match a document that was previously uploaded and stored in the session.
Return Value
Returns a Flask JSON response. On success (200): {'message': 'Document removed successfully'}. On document not found (404): {'error': 'Document not found'}. On server error (500): {'error': 'Failed to remove document'}. The response includes appropriate HTTP status codes.
Dependencies
flaskoslogging
Required Imports
from flask import jsonify
from flask import session
import os
import logging
Usage Example
# Flask application setup
from flask import Flask, session, jsonify
import os
import logging
app = Flask(__name__)
app.secret_key = 'your-secret-key'
logger = logging.getLogger(__name__)
# Assuming require_auth decorator is defined
def require_auth(f):
def wrapper(*args, **kwargs):
# Authentication logic here
return f(*args, **kwargs)
return wrapper
@app.route('/api/remove-document/<document_id>', methods=['DELETE'])
@require_auth
def api_remove_document(document_id):
# Function implementation here
pass
# Client-side usage (JavaScript fetch example):
# fetch('/api/remove-document/abc123', {
# method: 'DELETE',
# headers: {
# 'Content-Type': 'application/json'
# }
# })
# .then(response => response.json())
# .then(data => console.log(data.message))
# .catch(error => console.error('Error:', error));
Best Practices
- Always check if the document exists in the session before attempting to delete it
- Use try-except blocks for file system operations as files may be locked or already deleted
- Clean up temporary directories after removing files, but handle cases where directory is not empty
- Log warnings for file cleanup failures rather than raising errors, as the session cleanup is more critical
- Return appropriate HTTP status codes (404 for not found, 500 for server errors)
- Ensure the require_auth decorator is applied to prevent unauthorized document deletion
- The session must be properly configured with a secret key for secure session management
- Consider implementing additional authorization checks to ensure users can only delete their own documents
- The 'uploaded_documents' session structure should include 'file_path' key for proper cleanup
- Use os.path.exists() checks before attempting file operations to avoid exceptions
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_remove_document_v1 91.6% similar
-
function api_delete_chat_uploaded_document 83.0% similar
-
function api_delete_document 80.4% similar
-
function delete_document_v1 79.9% similar
-
function api_delete_section 75.6% similar