🔍 Code Extractor

function api_replace_section_content

Maturity: 50

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.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
1226 - 1260
Complexity:
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

  • flask
  • logging
  • datetime

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_update_section 81.7% similar

    REST API endpoint that updates an existing section within a document, allowing modification of title, content, type, and level properties with authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_delete_section 75.9% similar

    Flask API endpoint that deletes a specific section from a document after validating user authorization and document existence.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function update_data_section_content 75.9% similar

    Flask API endpoint that updates the content of a data section, setting both current_content and analysis_conclusions fields to the provided content value.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function update_text_section 75.7% similar

    Flask API endpoint that updates either the title or content of a text section, with ownership verification and version tracking.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_create_section 75.0% similar

    Flask API endpoint that creates a new section within a specified document, handling section positioning, type, level, title, and content with proper authentication and authorization checks.

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