function duplicate_text_section
Flask API endpoint that creates a duplicate of an existing text section with ownership verification and optional custom title.
/tf/active/vicechatdev/vice_ai/new_app.py
1698 - 1729
moderate
Purpose
This endpoint allows authenticated users to duplicate their own text sections. It verifies ownership before duplication, creates a copy with either a custom title or a default 'Copy of' prefix, and returns both the original section ID and the new duplicated section data. This is useful for creating templates or variations of existing content without manual recreation.
Source Code
def duplicate_text_section(section_id):
"""Create a duplicate of an existing text section"""
try:
user_email = get_current_user()
data = request.get_json()
# 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
new_title = data.get('title', f"Copy of {text_section.title}")
# Create duplicate
new_section = text_section_service.duplicate_text_section(
section_id,
user_email,
new_title
)
if new_section:
return jsonify({
'success': True,
'original_section_id': section_id,
'new_section': new_section.to_dict()
})
else:
return jsonify({'error': 'Failed to duplicate text section'}), 500
except Exception as e:
logger.error(f"Error duplicating 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 (likely UUID) of the text section to duplicate. Must be a valid section ID that exists in the database and belongs to the authenticated user. Passed as a URL path parameter.
Return Value
Returns a Flask JSON response. On success (200): {'success': True, 'original_section_id': str, 'new_section': dict} where new_section contains the duplicated section's data via to_dict() method. On error: 404 if section not found or access denied, 500 if duplication fails, 400 for other exceptions. All error responses include {'error': str} with error message.
Dependencies
flasklogging
Required Imports
from flask import request, jsonify
import logging
Usage Example
# Client-side usage (JavaScript fetch example)
fetch('/api/text-sections/abc-123-def/duplicate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
},
body: JSON.stringify({
title: 'My Custom Copy Title'
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
console.log('Original ID:', data.original_section_id);
console.log('New section:', data.new_section);
} else {
console.error('Error:', data.error);
}
});
# Server-side test example
# Assuming Flask test client
response = client.post(
'/api/text-sections/section-uuid-123/duplicate',
json={'title': 'New Copy'},
headers={'Authorization': 'Bearer token'}
)
assert response.status_code == 200
data = response.get_json()
assert data['success'] == True
assert 'new_section' in data
Best Practices
- Always verify ownership before allowing duplication to prevent unauthorized access
- The endpoint requires authentication via the require_auth decorator
- Provide a custom title in the request body to override the default 'Copy of' prefix
- Handle all three possible error status codes (404, 500, 400) in client code
- The function uses try-except to catch and log all exceptions for debugging
- Ownership is verified by comparing text_section.owner with the authenticated user's email
- If no title is provided in the request, a default title with 'Copy of' prefix is used
- The service layer (text_section_service) handles the actual duplication logic
- Error logging is performed before returning error responses for troubleshooting
- The endpoint returns the complete new section data via to_dict() for immediate use by the client
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_text_section_for_document 77.3% similar
-
function create_text_section 76.1% similar
-
function update_text_section 74.6% similar
-
function add_existing_section_to_document 74.5% similar
-
function delete_text_section 73.9% similar