🔍 Code Extractor

function get_text_section_usage

Maturity: 49

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.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
1734 - 1756
Complexity:
moderate

Purpose

This endpoint allows authenticated users to discover which documents are using a particular text section they own. It's useful for understanding dependencies before modifying or deleting a text section, and for tracking content reuse across documents. The function enforces access control by verifying the requesting user owns the text section.

Source Code

def get_text_section_usage(section_id):
    """Get information about which documents use a specific text section"""
    try:
        user_email = get_current_user()
        
        # Verify section ownership
        text_section = text_section_service.get_text_section(section_id)
        if not text_section or text_section.owner != user_email:
            return jsonify({'error': 'Section not found or access denied'}), 404
        
        # Get documents that use this text section
        usage_info = document_service.get_text_section_usage(section_id, user_email)
        
        return jsonify({
            'success': True,
            'section_id': section_id,
            'section_title': text_section.title,
            'usage': usage_info
        })
        
    except Exception as e:
        logger.error(f"Error getting text section usage: {e}")
        return jsonify({'error': str(e)}), 400

Parameters

Name Type Default Kind
section_id - - positional_or_keyword

Parameter Details

section_id: String identifier (likely UUID) of the text section to query. This ID is extracted from the URL path parameter. The section must exist and be owned by the authenticated user, otherwise a 404 error is returned.

Return Value

Returns a Flask JSON response tuple. On success (200): {'success': True, 'section_id': str, 'section_title': str, 'usage': usage_info_object} where usage_info contains document references. On error: ({'error': str}, 404) for not found/access denied, or ({'error': str}, 400) for other exceptions. The usage_info structure is determined by document_service.get_text_section_usage().

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import logging

Usage Example

# This is a Flask route handler, not called directly
# Example HTTP request:
# GET /api/text-sections/abc-123-def-456/usage
# Headers: Authorization: Bearer <token>

# Response example (success):
# {
#   "success": true,
#   "section_id": "abc-123-def-456",
#   "section_title": "Introduction Template",
#   "usage": [
#     {"document_id": "doc-1", "document_title": "Report A"},
#     {"document_id": "doc-2", "document_title": "Report B"}
#   ]
# }

# To use in Flask app context:
# from flask import Flask
# app = Flask(__name__)
# 
# @app.route('/api/text-sections/<section_id>/usage', methods=['GET'])
# @require_auth
# def get_text_section_usage(section_id):
#     # function implementation
#     pass

Best Practices

  • Always verify ownership before returning sensitive data - this function correctly checks text_section.owner against user_email
  • Use try-except blocks to handle errors gracefully and return appropriate HTTP status codes
  • Log errors with sufficient context for debugging (includes error message in log)
  • Return consistent JSON response structure with 'success' flag for easier client-side handling
  • Use 404 for both 'not found' and 'access denied' to avoid leaking information about resource existence
  • The require_auth decorator should be applied before this function to ensure user is authenticated
  • Consider implementing rate limiting for API endpoints to prevent abuse
  • The function assumes text_section_service and document_service are properly initialized in the module scope
  • Ensure get_current_user() returns a consistent identifier (email) that matches the owner field in TextSection model

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_text_section 88.5% 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_document_text_sections 81.0% 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_versions 80.8% similar

    Flask API endpoint that retrieves all historical versions of a specific text section, with ownership verification and authentication required.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_text_sections 80.1% 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 74.3% 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