🔍 Code Extractor

function api_task_status

Maturity: 48

Flask API endpoint that retrieves and returns the status of asynchronous tasks (chat or indexing operations) by task ID.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
1076 - 1095
Complexity:
simple

Purpose

This endpoint provides a RESTful API for polling the status of long-running asynchronous tasks. It returns different response structures based on task state (pending, completed, or failed), including progress information, timestamps, results on completion, or error messages on failure. This is commonly used in web applications to track background job progress without blocking the main thread.

Source Code

def api_task_status(task_id):
    """Get task status for chat or indexing operations"""
    task = get_task_status(task_id)
    
    if not task:
        return jsonify({'error': 'Task not found'}), 404
    
    response = {
        'status': task['status'],
        'progress': task.get('progress', ''),
        'created_at': task.get('created_at').isoformat() if task.get('created_at') else None
    }
    
    if task['status'] == 'completed':
        response['result'] = task.get('result')
        response['completed_at'] = task.get('completed_at').isoformat() if task.get('completed_at') else None
    elif task['status'] == 'failed':
        response['error'] = task.get('error', 'Unknown error')
    
    return jsonify(response)

Parameters

Name Type Default Kind
task_id - - positional_or_keyword

Parameter Details

task_id: String identifier for the task to query. This ID is typically generated when a task is created and returned to the client for subsequent status checks. Expected to be a unique identifier (likely UUID format) that corresponds to an entry in the task storage system.

Return Value

Returns a Flask JSON response tuple. On success (200): JSON object containing 'status' (string: task state), 'progress' (string: progress description), 'created_at' (ISO format datetime string), and conditionally 'result' (any: task output if completed), 'completed_at' (ISO format datetime string if completed), or 'error' (string: error message if failed). On failure (404): JSON object with 'error' key indicating task not found. Return type is tuple of (flask.Response, int) where int is HTTP status code.

Dependencies

  • flask

Required Imports

from flask import jsonify

Usage Example

# Assuming Flask app is set up and get_task_status is defined
from flask import Flask, jsonify
import requests

# Client-side usage example:
task_id = 'abc-123-def-456'  # Task ID received from task creation endpoint
response = requests.get(f'http://localhost:5000/api/task-status/{task_id}')

if response.status_code == 200:
    data = response.json()
    print(f"Status: {data['status']}")
    print(f"Progress: {data.get('progress', 'N/A')}")
    
    if data['status'] == 'completed':
        print(f"Result: {data['result']}")
    elif data['status'] == 'failed':
        print(f"Error: {data['error']}")
else:
    print('Task not found')

Best Practices

  • This endpoint should be called periodically (polling) by clients to check task status, but implement reasonable polling intervals (e.g., 1-5 seconds) to avoid overwhelming the server
  • Consider implementing WebSocket or Server-Sent Events (SSE) for real-time updates instead of polling for better performance
  • Ensure get_task_status() function implements proper error handling and returns None for non-existent tasks
  • Task IDs should be validated to prevent injection attacks if stored in databases
  • Consider adding authentication/authorization to prevent unauthorized access to task status information
  • Implement task cleanup mechanisms to remove old completed/failed tasks from storage to prevent memory leaks
  • The datetime.isoformat() calls assume task timestamps are datetime objects; ensure get_task_status() returns proper datetime types
  • Consider adding rate limiting to prevent abuse of this polling endpoint
  • Add logging for task status requests to help with debugging and monitoring

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_task_status 86.8% similar

    Flask API endpoint that retrieves the current status of a background task by its task ID from an in-memory active_tasks dictionary.

    From: /tf/active/vicechatdev/docchat/blueprint.py
  • function api_task_status_v1 85.0% similar

    Flask API endpoint that retrieves and returns the status of a background task, with user authorization checks.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function api_chat_status 84.9% similar

    Flask API endpoint that retrieves the detailed status of a chat task by delegating to the api_task_status function using the provided task_id.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_index_progress 81.4% similar

    Flask API endpoint that retrieves the current progress status of an asynchronous indexing task by its task ID.

    From: /tf/active/vicechatdev/docchat/app.py
  • function text_chat_get_progress 72.0% similar

    Flask API endpoint that retrieves the progress status of an asynchronous text chat job, particularly for multi-cycle web search operations.

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