Flask-Executor

1.0.0 · active · verified Thu Apr 16

Flask-Executor is an easy-to-use Flask wrapper for the concurrent.futures module that allows you to initialize and configure executors via common Flask application patterns. It provides a lightweight in-process task queue solution for Flask applications, making it suitable for managing background tasks without the overhead of separate worker processes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `Flask-Executor` with your Flask application and submit a simple background task using `executor.submit()`. Tasks are executed in a thread or process pool, and the route immediately returns a 202 Accepted response.

from flask import Flask, jsonify
from flask_executor import Executor
import time
import os

app = Flask(__name__)

# Configure executor (optional, defaults to ThreadPoolExecutor)
# app.config['EXECUTOR_TYPE'] = 'thread' # or 'process'
# app.config['EXECUTOR_MAX_WORKERS'] = 5 # or None

executor = Executor(app)

def long_running_task(duration):
    time.sleep(duration)
    return f"Task finished after {duration} seconds"

@app.route('/start-task/<int:duration>')
def start_task(duration):
    future = executor.submit(long_running_task, duration)
    # You can store the future_key if you want to retrieve results later
    # executor.submit_stored('my_task_key', long_running_task, duration)
    return jsonify({"message": f"Task submitted, will take {duration} seconds"}), 202

# Example for retrieving stored future (requires submit_stored instead of submit)
# @app.route('/get-task-result')
# def get_task_result():
#     if not executor.futures.done('my_task_key'):
#         return jsonify({'status': executor.futures._state('my_task_key')}), 202
#     future = executor.futures.pop('my_task_key')
#     return jsonify({'status': 'done', 'result': future.result()})

if __name__ == '__main__':
    # In a real application, consider using a production-ready WSGI server
    app.run(debug=True)

view raw JSON →