function create_document_v5
Flask API endpoint that creates a new document or duplicates an existing document with options to copy or reference sections.
/tf/active/vicechatdev/vice_ai/new_app.py
946 - 1023
moderate
Purpose
This endpoint handles document creation requests in a document management system. It supports two actions: creating a new empty document with a title and description, or duplicating an existing document either by copying all sections (full duplication) or by referencing the same sections (reference duplication). The endpoint enforces authentication and ownership verification for duplication operations.
Source Code
def create_document():
"""Create a new document or duplicate an existing one"""
user_email = get_current_user()
data = request.get_json()
logger.info(f"Creating document for user {user_email} with data: {data}")
try:
action = data.get('action', 'create_new') # 'create_new' or 'duplicate'
title = data.get('title', 'Untitled Document')
description = data.get('description', '')
source_document_id = data.get('source_document_id')
duplicate_sections = data.get('duplicate_sections', True)
logger.info(f"📋 Document creation request details:")
logger.info(f" Action: {action}")
logger.info(f" Title: {title}")
logger.info(f" Description: {description}")
logger.info(f" Source Document ID: {source_document_id}")
logger.info(f" Duplicate Sections: {duplicate_sections}")
logger.info(f" Raw Data Keys: {list(data.keys())}")
if action == 'duplicate':
# Duplicate existing document
source_document_id = data.get('source_document_id')
duplicate_sections = data.get('duplicate_sections', True) # Whether to duplicate or reference sections
logger.info(f"Duplication request - Source ID: {source_document_id}, Duplicate sections: {duplicate_sections}")
if not source_document_id:
return jsonify({'error': 'source_document_id is required for duplication'}), 400
# Verify source document exists and user has access
source_document = document_service.get_document(source_document_id)
if not source_document or source_document.owner != user_email:
return jsonify({'error': 'Source document not found or access denied'}), 404
if duplicate_sections:
# Full duplication: create copies of all text sections
logger.info(f"Calling duplicate_document for full duplication...")
document = document_service.duplicate_document(
source_document_id,
user_email,
title
)
logger.info(f"Full duplication result: {document.id if document else 'None'}, sections: {len(document.sections) if document else 0}")
else:
# Reference duplication: create new document but reference same text sections
logger.info(f"Calling duplicate_document_with_references...")
document = document_service.duplicate_document_with_references(
source_document_id,
user_email,
title,
description
)
logger.info(f"Reference duplication result: {document.id if document else 'None'}, sections: {len(document.sections) if document else 0}")
else:
logger.info(f"📝 Creating new empty document...")
# Create new empty document
document = document_service.create_document(
owner=user_email,
title=title,
description=description
)
if document:
logger.info(f"✅ New document created: {document.title} (ID: {document.id})")
logger.info(f"Document created successfully: {document.id}")
return jsonify({
'success': True,
'document': document.to_dict(),
'action': action
})
except Exception as e:
logger.error(f"Error creating document: {e}")
return jsonify({'error': str(e)}), 400
Return Value
Returns a JSON response with status code. On success (200): {'success': True, 'document': <document_dict>, 'action': <action_type>}. On error (400): {'error': <error_message>} for general errors. On error (404): {'error': 'Source document not found or access denied'} when source document doesn't exist or user lacks access.
Dependencies
flaskloggingtyping
Required Imports
from flask import request, jsonify
import logging
Usage Example
# Example 1: Create new document
import requests
response = requests.post(
'http://localhost:5000/api/documents',
json={
'action': 'create_new',
'title': 'My New Document',
'description': 'A document about data analysis'
},
headers={'Authorization': 'Bearer <token>'}
)
result = response.json()
print(f"Created document ID: {result['document']['id']}")
# Example 2: Duplicate document with full section copy
response = requests.post(
'http://localhost:5000/api/documents',
json={
'action': 'duplicate',
'source_document_id': 'doc-123',
'title': 'Copy of Original Document',
'duplicate_sections': True
},
headers={'Authorization': 'Bearer <token>'}
)
# Example 3: Duplicate document with section references
response = requests.post(
'http://localhost:5000/api/documents',
json={
'action': 'duplicate',
'source_document_id': 'doc-123',
'title': 'Reference to Original',
'description': 'Uses same sections as original',
'duplicate_sections': False
},
headers={'Authorization': 'Bearer <token>'}
)
Best Practices
- Always verify user authentication before allowing document operations
- Validate source_document_id exists and user has ownership before duplication
- Use appropriate HTTP status codes: 200 for success, 400 for bad requests, 404 for not found
- Log all document creation operations with detailed information for debugging
- Handle exceptions gracefully and return meaningful error messages to clients
- Ensure document_service methods are transactional to maintain data consistency
- Consider implementing rate limiting to prevent abuse of document creation
- Validate input data types and sanitize user inputs before processing
- Use the duplicate_sections flag carefully - full duplication creates independent copies while reference duplication shares sections
- Ensure proper cleanup of resources if document creation fails partway through
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_document_v7 83.1% similar
-
function api_create_document 77.6% similar
-
function create_text_section_for_document 76.4% similar
-
function api_create_section 75.4% similar
-
function get_document_v4 73.0% similar