🔍 Code Extractor

function get_document_text_sections

Maturity: 53

Flask API endpoint that retrieves all text and data sections for a specific document, verifying user ownership and returning sections sorted by position.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
1230 - 1269
Complexity:
moderate

Purpose

This endpoint serves as a REST API route to fetch all sections (both text and data types) associated with a document. It enforces authentication and authorization by verifying the requesting user owns the document before returning the sections. The sections are retrieved from separate services, enriched with position information, and returned in sorted order. This is typically used by frontend applications to display or edit document content.

Source Code

def get_document_text_sections(document_id):
    """Get all sections (text and data) for a specific document"""
    user_email = get_current_user()
    
    # Verify document ownership
    document = document_service.get_document(document_id)
    if not document or document.owner != user_email:
        return jsonify({'error': 'Document not found or access denied'}), 404
    
    try:
        # Get document with all sections
        text_sections = []
        data_sections_list = []
        
        for doc_section in document.sections:
            if doc_section.section_type == SectionType.TEXT:
                section = text_section_service.get_text_section(doc_section.section_id)
                if section:
                    section_dict = section.to_dict()
                    section_dict['position'] = doc_section.position
                    text_sections.append(section_dict)
            elif doc_section.section_type == SectionType.DATA:
                section = data_section_service.get_data_section(doc_section.section_id)
                if section:
                    section_dict = section.to_dict()
                    section_dict['position'] = doc_section.position
                    data_sections_list.append(section_dict)
        
        # Sort by position
        text_sections.sort(key=lambda x: x.get('position', 0))
        data_sections_list.sort(key=lambda x: x.get('position', 0))
        
        return jsonify({
            'text_sections': text_sections,
            'data_sections': data_sections_list
        })
        
    except Exception as e:
        logger.error(f"Error getting document sections: {e}")
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
document_id - - positional_or_keyword

Parameter Details

document_id: String identifier for the document whose sections should be retrieved. This is extracted from the URL path parameter and used to query the document and its associated sections.

Return Value

Returns a Flask JSON response. On success (200): a dictionary with 'text_sections' (list of text section dictionaries) and 'data_sections' (list of data section dictionaries), both sorted by position. On authorization failure (404): {'error': 'Document not found or access denied'}. On server error (500): {'error': '<error message>'}. Each section dictionary includes all section fields plus a 'position' field indicating its order in the document.

Dependencies

  • flask
  • logging
  • typing

Required Imports

from flask import jsonify
import logging
from models import SectionType
from services import TextSectionService
from services import DataSectionService
from services import DocumentService

Usage Example

# This is a Flask route handler, typically called via HTTP request
# Example HTTP request:
# GET /api/documents/abc123/text_sections
# Headers: Authorization: Bearer <token>

# Response example (success):
# {
#   "text_sections": [
#     {
#       "id": "section1",
#       "content": "Introduction text",
#       "position": 0,
#       "title": "Introduction"
#     },
#     {
#       "id": "section2",
#       "content": "Body text",
#       "position": 2,
#       "title": "Main Content"
#     }
#   ],
#   "data_sections": [
#     {
#       "id": "data1",
#       "data": {...},
#       "position": 1,
#       "title": "Chart Data"
#     }
#   ]
# }

# To call programmatically within Flask app:
import requests
response = requests.get(
    'http://localhost:5000/api/documents/abc123/text_sections',
    headers={'Authorization': 'Bearer <token>'}
)
if response.status_code == 200:
    sections = response.json()
    text_sections = sections['text_sections']
    data_sections = sections['data_sections']

Best Practices

  • Always verify document ownership before returning sensitive data
  • Use try-except blocks to handle service layer exceptions gracefully
  • Log errors with sufficient context for debugging
  • Sort sections by position to maintain document structure
  • Return consistent error response format across all error cases
  • Separate text and data sections in the response for easier client-side processing
  • Use service layer pattern to separate business logic from route handlers
  • Ensure the require_auth decorator is applied to protect the endpoint
  • Consider implementing pagination if documents can have many sections
  • Cache document sections if they are frequently accessed and rarely modified
  • Validate document_id format before querying to prevent injection attacks

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_text_sections 88.3% similar

    Flask API endpoint that retrieves text sections for the authenticated user with optional filtering by type, search query, tags, and uniqueness.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_available_sections_for_document 86.4% similar

    Flask API endpoint that retrieves text sections available to add to a specific document by filtering out sections already included in that document.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_document_v4 83.4% similar

    Flask API endpoint that retrieves a specific document with its text and data sections, including optional sharing information, for authenticated users.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_text_section_usage 81.0% similar

    Flask API endpoint that retrieves usage information for a specific text section, showing which documents reference it. Requires authentication and verifies section ownership before returning usage data.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_text_section 80.7% similar

    Flask API endpoint that retrieves a specific text section by ID with optional version history and usage information, enforcing ownership-based access control.

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