🔍 Code Extractor

function save_document

Maturity: 39

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

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
594 - 601
Complexity:
moderate

Purpose

This function provides a dual-persistence mechanism for document objects. It first acquires a thread-safe lock to update the document in the application's in-memory state dictionary, sets the document's updated_at timestamp to the current datetime, and then delegates to a separate function to persist the document to the file system. This ensures both fast in-memory access and durable storage.

Source Code

def save_document(document):
    """Save a document"""
    with app_state['locks']['documents']:
        app_state['documents'][document.id] = document
        document.updated_at = datetime.now()
    
    # Also save to file
    save_document_to_file(document)

Parameters

Name Type Default Kind
document - - positional_or_keyword

Parameter Details

document: A document object that must have at minimum an 'id' attribute (used as the dictionary key) and an 'updated_at' attribute (set to current datetime). The object should be compatible with the save_document_to_file function for file persistence.

Return Value

This function does not return any value (implicitly returns None). The side effects are: (1) the document is stored/updated in app_state['documents'] dictionary with document.id as key, (2) document.updated_at is modified to current datetime, and (3) the document is persisted to file via save_document_to_file function.

Dependencies

  • datetime
  • threading

Required Imports

from datetime import datetime
from threading import Lock

Usage Example

from datetime import datetime
from threading import Lock

# Setup required global state
app_state = {
    'locks': {'documents': Lock()},
    'documents': {}
}

# Define the dependency function
def save_document_to_file(document):
    # Implementation to save document to file
    pass

# Create a document object
class Document:
    def __init__(self, doc_id, content):
        self.id = doc_id
        self.content = content
        self.updated_at = None

# Use the function
doc = Document('doc123', 'Sample content')
save_document(doc)
print(f"Document saved with timestamp: {doc.updated_at}")

Best Practices

  • Ensure app_state is properly initialized before calling this function to avoid KeyError exceptions
  • The document object must have both 'id' and 'updated_at' attributes or AttributeError will be raised
  • This function modifies the document object in-place by setting updated_at, so be aware of side effects
  • The function uses a lock for thread-safety, but save_document_to_file is called outside the lock - ensure this function is also thread-safe if needed
  • Consider error handling for cases where save_document_to_file fails, as the in-memory state will be updated but file persistence may fail
  • The lock is acquired using a context manager (with statement), ensuring proper release even if exceptions occur
  • Document IDs should be unique to prevent overwriting existing documents unintentionally

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function save_document_to_file 72.0% 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 store_document 70.8% similar

    Thread-safe function that stores document information (file path, text content, metadata) in a global dictionary indexed by user email and document ID.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function store_uploaded_document 69.1% similar

    Stores uploaded document metadata and content in a thread-safe application state dictionary, organized by user email and document ID.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function store_uploaded_document_v1 69.0% similar

    Stores an uploaded document in a thread-safe global application state dictionary, organizing documents by user email and document ID with metadata including name, content, file type, and upload timestamp.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function remove_uploaded_document 63.9% similar

    Removes a specific uploaded document from the application state for a given user, with thread-safe locking and automatic cleanup of empty user entries.

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