function delete_document_file
Deletes a document file from the file system based on the provided document ID, removing the corresponding JSON file from the DOCUMENTS_DIR directory.
/tf/active/vicechatdev/vice_ai/complex_app.py
131 - 139
simple
Purpose
This function is used to permanently remove document files from storage when they are no longer needed. It constructs the file path using the document ID, checks if the file exists, and deletes it. The function includes error handling and logging to track successful deletions and failures. This is typically used in document management systems when users delete documents or during cleanup operations.
Source Code
def delete_document_file(doc_id):
"""Delete document file"""
try:
file_path = os.path.join(DOCUMENTS_DIR, f"{doc_id}.json")
if os.path.exists(file_path):
os.remove(file_path)
logger.info(f"🗑️ Document file deleted: {doc_id}")
except Exception as e:
logger.error(f"❌ Failed to delete document file {doc_id}: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
doc_id |
- | - | positional_or_keyword |
Parameter Details
doc_id: The unique identifier for the document to be deleted. This ID is used to construct the filename as '{doc_id}.json' within the DOCUMENTS_DIR directory. Expected to be a string or value that can be formatted into a filename.
Return Value
This function does not return any value (implicitly returns None). It performs a side effect of deleting a file from the file system and logs the operation result.
Dependencies
oslogging
Required Imports
import os
import logging
Usage Example
import os
import logging
# Setup logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# Define documents directory
DOCUMENTS_DIR = '/path/to/documents'
# Ensure directory exists
os.makedirs(DOCUMENTS_DIR, exist_ok=True)
# Create a test document file
doc_id = 'test_doc_123'
test_file_path = os.path.join(DOCUMENTS_DIR, f'{doc_id}.json')
with open(test_file_path, 'w') as f:
f.write('{"title": "Test Document"}')
# Delete the document file
delete_document_file(doc_id)
# Verify deletion
if not os.path.exists(test_file_path):
print('Document successfully deleted')
Best Practices
- Ensure DOCUMENTS_DIR is properly defined and accessible before calling this function
- The function silently handles non-existent files, so verify file existence separately if needed
- Consider implementing backup or soft-delete mechanisms before calling this function for critical documents
- Ensure proper permissions are set on the DOCUMENTS_DIR to allow file deletion
- The function catches all exceptions, which may hide specific error types - consider more granular exception handling for production use
- Consider adding a return value (boolean) to indicate success/failure for better error handling in calling code
- Validate doc_id input to prevent path traversal attacks if user input is involved
- Consider implementing transaction-like behavior if this deletion is part of a larger operation that might need rollback
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function remove_user_document 70.8% similar
-
function save_document_to_file 66.6% similar
-
function delete_document_from_filecloud 64.0% similar
-
function api_remove_document 62.1% similar
-
function remove_uploaded_document_v1 60.9% similar