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.
pip install flask-executorVerified import paths — ran on the pinned version, not inferred.
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.
Pass all necessary data (like configuration values or request parameters) explicitly as arguments to tasks running in a `ProcessPoolExecutor`. Avoid relying on automatic context propagation.
Be aware of context immutability. If bidirectional communication or shared state is needed, implement explicit mechanisms (e.g., database updates, message queues, shared memory with proper locking) instead of relying on context modification.
For robust database operations in background tasks, consider either manually pushing a new application/request context for each task (if thread-safe), defining a custom thread-aware `scopefunc` for `Flask-SQLAlchemy`'s session, or re-establishing database sessions within each task. The library owner suggests basic usage works, but complex failure scenarios may require explicit handling.
For `ProcessPoolExecutor`, pass all necessary data explicitly to the task function as arguments. For `ThreadPoolExecutor`, ensure `Flask-Executor` is initialized correctly with the Flask app, as it is designed to copy the context. However, be mindful of the immutability of copied contexts and their limited lifespan.
Explicitly pass any required configuration values as arguments to your task functions. Alternatively, if using named executors, configuration can be set via environment variables prefixed with the executor's name (e.g., `CUSTOM_EXECUTOR_TYPE`).
Refactor your task to avoid passing unpickleable objects to a `ProcessPoolExecutor`. Instead, re-create necessary resources (like database sessions) within the task function itself, or switch to a `ThreadPoolExecutor` if the task is I/O-bound and doesn't require separate processes, as threads share memory and don't require pickling for context. Ensure `app.config['EXECUTOR_TYPE'] = 'thread'`.