🔍 Code Extractor

function add_data_section_to_document

Maturity: 50

Flask API endpoint that adds a data section to a document, either by creating a new data section or linking an existing one, with ownership verification.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
5847 - 5913
Complexity:
moderate

Purpose

This endpoint handles POST requests to add data analysis sections to documents. It supports two actions: 'create_new' to create and attach a new data section, or 'add_existing' to link an existing data section. The function verifies document and section ownership, validates user permissions, and manages the relationship between documents and data sections at specified positions.

Source Code

def add_data_section_to_document(document_id):
    """Add a data section to a document"""
    user_email = get_current_user()
    data = request.get_json()
    
    # 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:
        action = data.get('action', 'create_new')
        position = data.get('position', -1)
        
        if action == 'create_new':
            # Create new data section
            title = data.get('title', 'Untitled Data Analysis')
            description = data.get('description', '')
            
            data_section = data_section_service.create_data_section(
                owner=user_email,
                title=title,
                description=description
            )
            
            # Add to document
            document_service.add_section_to_document(
                document_id=document_id,
                section_id=data_section.id,
                section_type=SectionType.DATA,
                position=position
            )
            
            return jsonify({
                'success': True,
                'section': data_section.to_dict()
            })
            
        elif action == 'add_existing':
            # Add existing data section to document
            section_id = data.get('section_id')
            if not section_id:
                return jsonify({'error': 'section_id required for add_existing action'}), 400
            
            # Verify section ownership
            data_section = data_section_service.get_data_section(section_id)
            if not data_section or data_section.owner != user_email:
                return jsonify({'error': 'Data section not found or access denied'}), 404
            
            # Add to document
            document_service.add_section_to_document(
                document_id=document_id,
                section_id=section_id,
                section_type=SectionType.DATA,
                position=position
            )
            
            return jsonify({
                'success': True,
                'section': data_section.to_dict()
            })
        else:
            return jsonify({'error': 'Invalid action'}), 400
            
    except Exception as e:
        logger.error(f"Error adding data section to document: {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 target document. Passed as a URL path parameter. Used to locate the document and verify ownership before adding the data section.

Return Value

Returns a Flask JSON response tuple. On success (200): {'success': True, 'section': <data_section_dict>} containing the data section details. On error: {'error': <error_message>} with status codes 400 (bad request/invalid action), 404 (document/section not found or access denied), or 500 (server error).

Dependencies

  • flask
  • logging

Required Imports

from flask import request, jsonify
import logging

Usage Example

# Example 1: Create new data section
import requests

headers = {'Authorization': 'Bearer <token>', 'Content-Type': 'application/json'}
data = {
    'action': 'create_new',
    'title': 'Sales Analysis Q4',
    'description': 'Quarterly sales data analysis',
    'position': 2
}
response = requests.post(
    'http://api.example.com/api/documents/doc123/data-sections',
    json=data,
    headers=headers
)
result = response.json()
print(result['section']['id'])

# Example 2: Add existing data section
data = {
    'action': 'add_existing',
    'section_id': 'section456',
    'position': -1
}
response = requests.post(
    'http://api.example.com/api/documents/doc123/data-sections',
    json=data,
    headers=headers
)
result = response.json()

Best Practices

  • Always verify document ownership before allowing modifications
  • Validate the 'action' parameter to ensure only supported actions are processed
  • Use position=-1 to append sections at the end of the document
  • Handle both create_new and add_existing actions with appropriate validation
  • Verify section ownership when adding existing sections to prevent unauthorized access
  • Include proper error handling and logging for debugging
  • Return consistent JSON response structures for success and error cases
  • Use appropriate HTTP status codes (400 for bad requests, 404 for not found, 500 for server errors)
  • Ensure the require_auth decorator is applied to protect the endpoint
  • Provide default values for optional parameters like title, description, and position

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function add_existing_data_section_to_document 95.6% similar

    Flask API endpoint that adds an existing data section to a document after verifying ownership and access permissions for both the document and data section.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_create_section 86.1% 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
  • function create_data_section 85.2% similar

    Flask API endpoint that creates a new data section for authenticated users, accepting title and description from JSON request body.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function add_existing_section_to_document 83.0% similar

    Flask API endpoint that adds an existing text section to a document with advanced positioning options, copy creation, and access control validation.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function create_text_section_for_document 82.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