function api_replace_section_content
API endpoint that replaces the content of a specific section within a document, storing the old content for potential undo operations and updating the section's timestamp.
/tf/active/vicechatdev/vice_ai/complex_app.py
1226 - 1260
moderate
Purpose
This Flask route handler provides a RESTful API endpoint for replacing section content in a document management system. It validates document ownership, ensures the section exists, replaces the content with new text (typically from a chat response), and maintains an audit trail by returning the old content. The function includes comprehensive error handling for missing documents, unauthorized access, missing sections, and empty content.
Source Code
def api_replace_section_content(doc_id, section_id):
"""Replace section content with chat response"""
try:
document = get_document(doc_id)
if not document:
return jsonify({'error': 'Document not found'}), 404
if document.author != get_user_id():
return jsonify({'error': 'Access denied'}), 403
section = document.get_section(section_id)
if not section:
return jsonify({'error': 'Section not found'}), 404
data = request.get_json()
new_content = data.get('content', '').strip()
if not new_content:
return jsonify({'error': 'Content cannot be empty'}), 400
# Store old content for potential undo
old_content = section.content
section.content = new_content
section.updated_at = datetime.now()
save_document(document)
return jsonify({
'section': section.to_dict(),
'old_content': old_content,
'message': 'Section content replaced successfully'
})
except Exception as e:
logger.error(f"Replace section content error: {e}")
return jsonify({'error': 'Failed to replace content'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
doc_id |
- | - | positional_or_keyword |
section_id |
- | - | positional_or_keyword |
Parameter Details
doc_id: String identifier for the document containing the section to be updated. Extracted from the URL path parameter. Used to retrieve the document from storage.
section_id: String identifier for the specific section within the document whose content should be replaced. Extracted from the URL path parameter. Used to locate the target section within the document structure.
Return Value
Returns a Flask JSON response tuple. On success (200): JSON object containing 'section' (dictionary representation of updated section via to_dict()), 'old_content' (string of previous content for undo), and 'message' (success confirmation). On error: JSON object with 'error' key and appropriate HTTP status code (404 for not found, 403 for access denied, 400 for empty content, 500 for server errors).
Dependencies
flaskloggingdatetime
Required Imports
from flask import jsonify
from flask import request
from datetime import datetime
import logging
Usage Example
# Client-side usage example (JavaScript fetch)
fetch('/api/documents/doc123/sections/section456/replace-content', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
},
body: JSON.stringify({
content: 'This is the new section content from chat response'
})
})
.then(response => response.json())
.then(data => {
console.log('Updated section:', data.section);
console.log('Old content for undo:', data.old_content);
})
.catch(error => console.error('Error:', error));
# Server-side test example (Python)
import requests
response = requests.post(
'http://localhost:5000/api/documents/doc123/sections/section456/replace-content',
json={'content': 'New content text'},
headers={'Authorization': 'Bearer <token>'}
)
if response.status_code == 200:
result = response.json()
print(f"Section updated: {result['section']}")
print(f"Old content: {result['old_content']}")
Best Practices
- Always authenticate requests using the require_auth decorator before allowing content modifications
- Verify document ownership before allowing updates to prevent unauthorized modifications
- Validate that content is not empty to maintain data integrity
- Store old content before replacement to enable undo functionality
- Update timestamps (updated_at) when modifying content for proper audit trails
- Use try-except blocks to catch and log errors gracefully
- Return appropriate HTTP status codes (404, 403, 400, 500) for different error scenarios
- Strip whitespace from input content to avoid accidental empty submissions
- Persist changes immediately using save_document() to prevent data loss
- Log errors with sufficient context for debugging and monitoring
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_update_section 81.7% similar
-
function api_delete_section 75.9% similar
-
function update_data_section_content 75.9% similar
-
function update_text_section 75.7% similar
-
function api_create_section 75.0% similar