🔍 Code Extractor

function save_document_to_file

Maturity: 44

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

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
74 - 83
Complexity:
simple

Purpose

This function serializes a document object to JSON format and saves it to a designated documents directory. It ensures the directory structure exists before writing, logs success/failure, and handles exceptions gracefully. This is typically used for persistent storage of document metadata and content in a file-based storage system.

Source Code

def save_document_to_file(document):
    """Save document to file"""
    try:
        ensure_directories()
        file_path = os.path.join(DOCUMENTS_DIR, f"{document.id}.json")
        with open(file_path, 'w') as f:
            json.dump(document.to_dict(), f, indent=2)
        logger.info(f"💾 Document saved to file: {document.id}")
    except Exception as e:
        logger.error(f"❌ Failed to save document {document.id}: {e}")

Parameters

Name Type Default Kind
document - - positional_or_keyword

Parameter Details

document: A document object that must have an 'id' attribute (used for filename) and a 'to_dict()' method that returns a dictionary representation suitable for JSON serialization. The object likely represents a document entity with metadata and content.

Return Value

This function does not return any value (implicitly returns None). Side effects include: creating a JSON file in the DOCUMENTS_DIR directory, logging success/error messages via the logger object.

Dependencies

  • os
  • json
  • logging

Required Imports

import os
import json
import logging

Usage Example

import os
import json
import logging

# Setup
DOCUMENTS_DIR = './documents'
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

def ensure_directories():
    os.makedirs(DOCUMENTS_DIR, exist_ok=True)

# Document class example
class Document:
    def __init__(self, doc_id, title, content):
        self.id = doc_id
        self.title = title
        self.content = content
    
    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'content': self.content
        }

# Usage
doc = Document('doc123', 'Sample Document', 'This is the content')
save_document_to_file(doc)
# Creates: ./documents/doc123.json with the document data

Best Practices

  • Ensure the document object has a unique 'id' attribute to prevent file overwrites
  • The document.to_dict() method should return only JSON-serializable data types (strings, numbers, lists, dicts, booleans, None)
  • DOCUMENTS_DIR should be an absolute path or properly configured relative path to avoid file location issues
  • Consider implementing file locking mechanisms if multiple processes/threads might write to the same document simultaneously
  • The function silently catches all exceptions - consider whether specific exception types should be handled differently
  • Ensure proper permissions exist for writing to DOCUMENTS_DIR before calling this function
  • The indent=2 parameter in json.dump makes files human-readable but increases file size - adjust based on needs

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function save_document 72.0% similar

    Saves a document object to both in-memory application state and persistent file storage, updating its timestamp in the process.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function save_chat_session_to_file 66.9% similar

    Persists a chat session object to a JSON file in the designated chat sessions directory, using the session's ID as the filename.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function delete_document_file 66.6% similar

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

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function load_document_from_file 64.8% similar

    Loads a document from a JSON file stored in a documents directory, deserializes it into a ComplexDocument object, and returns it.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function save_session_to_disk 63.8% similar

    Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings.

    From: /tf/active/vicechatdev/docchat/app.py
← Back to Browse