🔍 Code Extractor

function get_text_sections

Maturity: 51

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

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
508 - 558
Complexity:
moderate

Purpose

This endpoint serves as a REST API to fetch text sections belonging to the current authenticated user. It supports two modes: retrieving all sections or only unique sections (latest versions). The endpoint provides flexible filtering capabilities including section type, text search, and tag-based filtering. It's designed to support document management systems where users need to query and retrieve their text content with various criteria.

Source Code

def get_text_sections():
    """Get all text sections for current user with document information"""
    user_email = get_current_user()
    
    # Get query parameters
    section_type = request.args.get('type')
    search_query = request.args.get('q', '')
    tags = request.args.getlist('tags')
    unique_only = request.args.get('unique', 'false').lower() == 'true'
    
    try:
        if unique_only:
            # Get unique sections (latest versions only) with document info
            text_sections = text_section_service.get_unique_user_text_sections(user_email)
            
            # Apply filters if provided
            if section_type:
                text_sections = [s for s in text_sections if s.get('section_type') == section_type]
            if search_query:
                text_sections = [s for s in text_sections 
                               if search_query.lower() in s.get('title', '').lower() 
                               or search_query.lower() in s.get('current_content', '').lower()]
            if tags:
                text_sections = [s for s in text_sections 
                               if any(tag in s.get('tags', []) for tag in tags)]
        else:
            # Get all sections using existing search method
            if section_type:
                try:
                    section_type = SectionType(section_type)
                except ValueError:
                    section_type = None
            
            # Search text sections
            sections = text_section_service.search_text_sections(
                owner=user_email,
                query=search_query,
                section_type=section_type,
                tags=tags
            )
            text_sections = [section.to_dict() for section in sections]
        
        return jsonify({
            'text_sections': text_sections,
            'count': len(text_sections),
            'unique_only': unique_only
        })
        
    except Exception as e:
        logger.error(f"Error getting text sections: {e}")
        return jsonify({'error': 'Failed to retrieve text sections'}), 500

Return Value

Returns a JSON response with status code 200 on success or 500 on error. Success response contains: 'text_sections' (list of section dictionaries with fields like title, content, tags, section_type), 'count' (integer number of sections returned), and 'unique_only' (boolean indicating if unique filtering was applied). Error response contains: 'error' (string error message).

Dependencies

  • flask
  • logging

Required Imports

from flask import Flask, request, jsonify, session
import logging
from models import SectionType
from services import TextSectionService

Usage Example

# Example API calls:
# Get all text sections for authenticated user
GET /api/text_sections

# Get unique sections only
GET /api/text_sections?unique=true

# Filter by section type
GET /api/text_sections?type=introduction

# Search in title and content
GET /api/text_sections?q=methodology

# Filter by tags
GET /api/text_sections?tags=research&tags=draft

# Combined filters
GET /api/text_sections?unique=true&type=conclusion&q=results&tags=final

# Response example:
{
  "text_sections": [
    {
      "id": "123",
      "title": "Introduction",
      "current_content": "This is the introduction...",
      "section_type": "introduction",
      "tags": ["draft", "research"],
      "document_id": "doc-456"
    }
  ],
  "count": 1,
  "unique_only": true
}

Best Practices

  • Always ensure the require_auth decorator is properly configured to prevent unauthorized access
  • The function handles both snake_case and kebab-case URL patterns (/api/text_sections and /api/text-sections)
  • When unique_only=true, filtering is done in-memory after fetching unique sections, which may be inefficient for large datasets
  • Invalid section_type values are silently ignored rather than returning an error
  • The search query performs case-insensitive substring matching on both title and content fields
  • Tag filtering uses OR logic - sections matching any of the provided tags are included
  • Error handling catches all exceptions and returns a generic 500 error; consider more specific error handling for production
  • The function depends on get_current_user() to retrieve the authenticated user's email from session
  • Consider implementing pagination for large result sets to improve performance
  • The text_section_service must be properly initialized before this endpoint is called

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_text_sections 88.3% similar

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

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_text_section 82.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
  • function get_text_section_usage 80.1% 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_all_data_sections 79.5% similar

    Flask API endpoint that retrieves all data sections associated with the currently authenticated user and returns them as JSON.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_available_sections_for_document 78.0% 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
← Back to Browse