function save_document_to_file
Persists a document object to the filesystem as a JSON file, using the document's ID as the filename.
/tf/active/vicechatdev/vice_ai/complex_app.py
74 - 83
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
osjsonlogging
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
-
function save_chat_session_to_file 66.9% similar
-
function delete_document_file 66.6% similar
-
function load_document_from_file 64.8% similar
-
function save_session_to_disk 63.8% similar