🔍 Code Extractor

function create_document_v6

Maturity: 48

Creates a new ComplexDocument instance with a unique UUID, stores it in application state with thread-safe locking, persists it to file, and logs the creation.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
565 - 576
Complexity:
moderate

Purpose

This function serves as a factory method for creating and initializing ComplexDocument objects in a multi-threaded Flask application. It handles the complete lifecycle of document creation including ID generation, in-memory storage with thread synchronization, file persistence, and audit logging. It's designed for use in document management systems where documents need to be tracked both in memory and on disk.

Source Code

def create_document(title, author):
    """Create a new complex document"""
    doc_id = str(uuid.uuid4())
    document = ComplexDocument(doc_id, title, author)
    
    # Save to memory and file
    with app_state['locks']['documents']:
        app_state['documents'][doc_id] = document
    save_document_to_file(document)
    
    logger.info(f"Created new document: {title} (ID: {doc_id})")
    return document

Parameters

Name Type Default Kind
title - - positional_or_keyword
author - - positional_or_keyword

Parameter Details

title: String representing the title/name of the document to be created. This is used to initialize the ComplexDocument and appears in log messages.

author: String representing the author/creator of the document. This is stored as metadata in the ComplexDocument instance.

Return Value

Returns a ComplexDocument instance that has been fully initialized with a unique UUID identifier, the provided title and author, stored in the application's in-memory state dictionary, and persisted to file. The returned object can be used for further document operations.

Dependencies

  • uuid
  • threading
  • logging

Required Imports

import uuid
import threading
import logging

Usage Example

# Setup required before using create_document
import uuid
import logging
from threading import Lock

# Initialize logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# Initialize application state
app_state = {
    'documents': {},
    'locks': {
        'documents': Lock()
    }
}

# Define ComplexDocument class (example)
class ComplexDocument:
    def __init__(self, doc_id, title, author):
        self.id = doc_id
        self.title = title
        self.author = author
        self.created_at = datetime.now()

# Define save function (example)
def save_document_to_file(document):
    with open(f'documents/{document.id}.json', 'w') as f:
        json.dump({'id': document.id, 'title': document.title, 'author': document.author}, f)

# Use the function
document = create_document('Project Proposal', 'John Doe')
print(f'Created document with ID: {document.id}')

Best Practices

  • Ensure app_state dictionary is properly initialized before calling this function
  • The function assumes ComplexDocument class and save_document_to_file function are available in scope
  • Thread safety is handled via Lock context manager - ensure the lock exists in app_state['locks']['documents']
  • The function performs both in-memory and file storage - ensure adequate error handling in production
  • Consider wrapping in try-except blocks to handle potential file I/O errors from save_document_to_file
  • The UUID generation ensures unique document IDs but does not check for collisions in app_state
  • Logger should be configured at module level before using this function
  • In production, consider adding validation for title and author parameters (e.g., non-empty strings)
  • The function does not return error states - consider adding return value validation or exception handling

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function store_document 65.7% 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 create_document 63.1% similar

    Creates a new controlled document in a document management system with versioning, audit trails, and optional initial content.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function save_document 62.7% 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 create_document_v5 61.3% similar

    Flask API endpoint that creates a new document or duplicates an existing document with options to copy or reference sections.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_document_v7 61.3% similar

    Retrieves a document by its ID from an in-memory cache or loads it from persistent storage if not cached.

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