🔍 Code Extractor

function delete_document_file

Maturity: 41

Deletes a document file from the file system based on the provided document ID, removing the corresponding JSON file from the DOCUMENTS_DIR directory.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
131 - 139
Complexity:
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

  • os
  • logging

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function remove_user_document 70.8% similar

    Removes a specific document for a user by deleting the file from the filesystem and removing its metadata from the in-memory storage structure.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function save_document_to_file 66.6% similar

    Persists a document object to the filesystem as a JSON file, using the document's ID as the filename.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function delete_document_from_filecloud 64.0% similar

    Deletes a document and its associated folder from FileCloud storage, with permission checks, audit logging, and error handling.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function api_remove_document 62.1% similar

    Flask API endpoint that removes an uploaded document from the session and deletes its associated file from the filesystem.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function remove_uploaded_document_v1 60.9% similar

    Removes a specific uploaded document from a user's document collection in the application state, with thread-safe locking and automatic cleanup of empty user entries.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
← Back to Browse