🔍 Code Extractor

function update_text_section

Maturity: 50

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

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
632 - 683
Complexity:
moderate

Purpose

This endpoint handles PUT requests to update text sections in a document management system. It verifies user ownership, supports updating either the title or content (not both simultaneously), tracks changes with summaries, and maintains version history. It's designed for collaborative document editing with audit trails.

Source Code

def update_text_section(section_id):
    """Update text section content or title"""
    data = request.get_json()
    user_email = get_current_user()
    
    # Verify ownership
    text_section = text_section_service.get_text_section(section_id)
    if not text_section or text_section.owner != user_email:
        return jsonify({'error': 'Text section not found or access denied'}), 404
    
    try:
        success = False
        
        # Check if updating title
        if 'title' in data:
            new_title = data.get('title', '').strip()
            if new_title:
                success = text_section_service.update_text_section_title(section_id, new_title)
                change_type = 'title'
            else:
                return jsonify({'error': 'Title cannot be empty'}), 400
        
        # Check if updating content
        elif 'content' in data:
            new_content = data.get('content', text_section.current_content)
            change_summary = data.get('change_summary', 'Content updated')
            
            success = text_section_service.update_text_section_content(
                section_id=section_id,
                new_content=new_content,
                author=user_email,
                change_summary=change_summary,
                generated_by_ai=data.get('generated_by_ai', False)
            )
            change_type = 'content'
        else:
            return jsonify({'error': 'No title or content provided for update'}), 400
        
        if success:
            # Get updated text section
            updated_section = text_section_service.get_text_section(section_id)
            return jsonify({
                'success': True,
                'text_section': updated_section.to_dict(),
                'change_type': change_type
            })
        else:
            return jsonify({'error': f'Failed to update text section {change_type}'}), 500
            
    except Exception as e:
        logger.error(f"Error updating text section: {e}")
        return jsonify({'error': str(e)}), 400

Parameters

Name Type Default Kind
section_id - - positional_or_keyword

Parameter Details

section_id: String identifier for the text section to update. Must correspond to an existing text section in the database that the authenticated user owns.

Return Value

Returns a JSON response with HTTP status code. On success (200): {'success': True, 'text_section': <dict representation of updated section>, 'change_type': 'title'|'content'}. On error: {'error': <error message>} with status 400 (bad request), 404 (not found/access denied), or 500 (server error).

Dependencies

  • flask
  • logging

Required Imports

from flask import request, jsonify
import logging

Usage Example

# Update title
import requests

headers = {'Authorization': 'Bearer <token>', 'Content-Type': 'application/json'}

# Update title
response = requests.put(
    'http://localhost:5000/api/text-sections/section-123',
    json={'title': 'New Section Title'},
    headers=headers
)
print(response.json())
# Output: {'success': True, 'text_section': {...}, 'change_type': 'title'}

# Update content
response = requests.put(
    'http://localhost:5000/api/text-sections/section-123',
    json={
        'content': 'Updated content text',
        'change_summary': 'Fixed typos and updated statistics',
        'generated_by_ai': False
    },
    headers=headers
)
print(response.json())
# Output: {'success': True, 'text_section': {...}, 'change_type': 'content'}

Best Practices

  • Always verify user ownership before allowing updates to prevent unauthorized access
  • Only one field (title or content) can be updated per request - send separate requests for multiple changes
  • Title updates require non-empty strings; empty or whitespace-only titles are rejected
  • Content updates support optional change_summary parameter for audit trail documentation
  • Set generated_by_ai flag to true when content is AI-generated for proper tracking
  • Handle 404 responses which can indicate either non-existent section or access denial
  • The endpoint supports both /api/text_sections/ and /api/text-sections/ URL patterns
  • Ensure proper authentication token is included in requests via require_auth decorator
  • Version history is automatically maintained for content updates
  • Error responses include descriptive messages for debugging

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_update_section 83.0% 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 update_data_section 80.8% similar

    Flask API endpoint that updates an existing data section's metadata and content fields for authenticated users with ownership verification.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function update_data_section_content 80.7% 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 create_text_section 79.0% similar

    Flask API endpoint that creates a new text section with specified title, type, level, and content for an authenticated user.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function create_text_section_for_document 78.7% similar

    Flask API endpoint that creates or adds text sections to a document with three action modes: creating new sections, adding existing sections, or duplicating existing sections.

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