function api_delete_document
REST API endpoint that deletes a document from the application state after verifying the user's ownership and authentication.
/tf/active/vicechatdev/vice_ai/complex_app.py
799 - 815
moderate
Purpose
This function serves as a DELETE endpoint for document management. It authenticates the user, verifies document existence, checks ownership permissions, and removes the document from the application's in-memory storage using thread-safe locking mechanisms. It's part of a Flask-based document management system with role-based access control.
Source Code
def api_delete_document(doc_id):
"""Delete a document"""
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
with app_state['locks']['documents']:
del app_state['documents'][doc_id]
return jsonify({'message': 'Document deleted successfully'})
except Exception as e:
logger.error(f"Delete document error: {e}")
return jsonify({'error': 'Failed to delete document'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
doc_id |
- | - | positional_or_keyword |
Parameter Details
doc_id: String identifier for the document to be deleted. This is extracted from the URL path parameter and used to locate the document in the app_state['documents'] dictionary. Must correspond to an existing document ID.
Return Value
Returns a Flask JSON response tuple. On success: ({'message': 'Document deleted successfully'}, 200). On document not found: ({'error': 'Document not found'}, 404). On access denied: ({'error': 'Access denied'}, 403). On exception: ({'error': 'Failed to delete document'}, 500). Each return is a tuple of (json_response, http_status_code).
Dependencies
flask
Required Imports
from flask import jsonify
Usage Example
# This is a Flask route handler, typically called via HTTP DELETE request
# Example HTTP request:
# DELETE /api/documents/abc123
# Headers: Authorization: Bearer <token>
# Internal usage context:
import requests
# Assuming Flask app is running on localhost:5000
response = requests.delete(
'http://localhost:5000/api/documents/abc123',
headers={'Authorization': 'Bearer your_auth_token'}
)
if response.status_code == 200:
print(response.json()) # {'message': 'Document deleted successfully'}
elif response.status_code == 404:
print('Document not found')
elif response.status_code == 403:
print('Access denied - not the document owner')
else:
print('Error deleting document')
Best Practices
- Always verify user authentication before allowing document deletion (handled by require_auth decorator)
- Check document ownership before deletion to prevent unauthorized access
- Use thread-safe locking when modifying shared application state to prevent race conditions
- Return appropriate HTTP status codes (404 for not found, 403 for forbidden, 500 for server errors)
- Log errors for debugging and monitoring purposes
- Handle exceptions gracefully to prevent application crashes
- Consider implementing soft deletes instead of hard deletes for data recovery
- Consider adding audit logging to track who deleted what and when
- Ensure the get_document and get_user_id helper functions are properly implemented
- Consider cascading deletes if documents have related resources (files, metadata, etc.)
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function delete_document_v1 90.1% similar
-
function api_remove_document_v1 83.6% similar
-
function api_delete_chat_uploaded_document 80.9% similar
-
function api_remove_document 80.4% similar
-
function api_delete_section 79.9% similar