Registry / web-framework / flask-threads

flask-threads

JSON →
library0.2.0pypypi✓ verified 30d ago

Flask-Threads is a helper library designed to simplify working with threads within Flask applications. It addresses the common challenge of maintaining the Flask application context (e.g., `flask.g`, `request`) when executing code in background threads or using concurrent futures, which are typically thread-local. The library ensures that thread-local proxies remain accessible, preventing `RuntimeError` exceptions that occur when trying to access context outside the main request thread. The current version is 0.2.0, released on May 20, 2025, with an infrequent release cadence, primarily focusing on Flask compatibility.

pip install Flask-Threads
INSTALL
IMPORT
SIG · FLASK-THREADS
F
flask-threads
web-frameworkpythonv0.2.0
Install
2.3s avg
Import
498ms
Disk
21MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v0.2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.522s · 22.5MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 2.3s · import 0.474s · 23MB
21MB installed
● package 21MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

AppContextThread
✓ from flaskthreads import AppContextThread
ThreadPoolWithAppContextExecutor
✓ from flaskthreads import ThreadPoolWithAppContextExecutor

This example demonstrates how to use `AppContextThread` and `ThreadPoolWithAppContextExecutor` to run background tasks while retaining access to Flask's application context, specifically `flask.g`. The `user-id` is set in `flask.g` within the main request thread and then accessed correctly by the function running in a separate thread.

from flask import g, request, Flask from flaskthreads import AppContextThread, ThreadPoolWithAppContextExecutor import time app = Flask('my_app') def do_some_user_work_in_another_thread(): # Accessing flask.g from a different thread, enabled by Flask-Threads user_id = g.user_id print(f"[Thread] User ID from g: {user_id}") time.sleep(1) # Simulate work return f"Processed user {user_id}" @app.route('/user/thread') def get_user_with_thread(): g.user_id = request.headers.get('user-id', 'default_user_id_thread') print(f"[Main] Setting g.user_id: {g.user_id}") t = AppContextThread(target=do_some_user_work_in_another_thread) t.start() t.join() # Wait for the thread to complete return 'OK via AppContextThread' @app.route('/user/executor') def get_user_with_executor(): g.user_id = request.headers.get('user-id', 'default_user_id_executor') print(f"[Main] Setting g.user_id: {g.user_id}") with ThreadPoolWithAppContextExecutor(max_workers=2) as pool: future = pool.submit(do_some_user_work_in_another_thread) result = future.result() # Wait for the future to complete print(f"[Main] Future result: {result}") return 'OK via ThreadPoolWithAppContextExecutor' if __name__ == '__main__': # For demonstration, use a simple run. In production, use a WSGI server. # Set 'user-id' header (e.g., with curl -H 'user-id: 123' http://127.0.0.1:5000/user/thread) app.run(debug=True, use_reloader=False) # use_reloader=False to avoid double thread start in dev
Debug
Known issues
breakingOlder versions of Flask-Threads might not be compatible with Flask versions 3.0.0 and above.
fix
Upgrade to Flask-Threads version 0.2.0 or newer: `pip install --upgrade Flask-Threads`. Ensure your Flask version is compatible.
affects: <0.2.0
gotchaWhen running Flask in development mode with `debug=True`, Flask's reloader often starts the application twice. This can lead to background threads (including those managed by Flask-Threads) being initialized and run twice, causing unexpected behavior.
fix
To prevent this in development, run your Flask application with `app.run(debug=True, use_reloader=False)`. For production, use a WSGI server like Gunicorn or uWSGI, which manage processes differently and typically don't have this issue.
affects: All versions
gotchaWhile Flask-Threads helps maintain application context in background threads, it's crucial to understand that Flask's `request`, `g`, and `session` proxies are fundamentally tied to a specific request's lifecycle and thread. Misusing them (e.g., trying to modify `request` state in a background thread or keeping the context alive unnecessarily long) can still lead to data leaks, errors, or unexpected behavior.
fix
Only access context-local objects in background threads for read-only purposes or when `flask-threads` explicitly manages the context copy. For complex, long-running background jobs, consider external task queues like Celery or RQ, and pass only plain, serializable data (like IDs or file paths) rather than Flask context objects.
affects: All versions
gotchaPython's Global Interpreter Lock (GIL) limits true CPU parallelism for threads. While `flask-threads` is excellent for I/O-bound tasks that need Flask context, it will not make CPU-bound tasks run faster by simply using more threads.
fix
For CPU-bound tasks, consider using multi-processing (e.g., Python's `multiprocessing` module or `concurrent.futures.ProcessPoolExecutor`), or dedicated worker queues, which can leverage multiple CPU cores.
affects: All versions
Errors
Common errors & fixes
RuntimeError: Working outside of application context.
This error occurs when you try to access Flask's application-level objects (like `current_app` or extensions) in a background thread without an active application context. Flask's contexts are thread-local, so a new thread does not automatically inherit the context from the main request thread.
fix
Wrap the code that accesses application context in the background thread with `app.app_context()` or use `flask-threads`'s `AppContextThread` or `ThreadPoolWithAppContextExecutor` to automatically manage the context. For example: `from flaskthreads import AppContextThread; t = AppContextThread(target=my_function, args=(app,)).start()`
RuntimeError: Working outside of request context.
This error arises when you attempt to use request-specific objects (like `request`, `session`, or `g`) in a background thread, as the request context is thread-local and is not automatically available in the new thread after the original request has ended or in a separate thread.
fix
Use `flask-threads`'s `AppContextThread` or `ThreadPoolWithAppContextExecutor`, which ensure that the request context from the original thread is properly propagated to the background thread. Alternatively, pass necessary data extracted from `request` or `g` as arguments to your background function, avoiding direct context access in the thread.
ModuleNotFoundError: No module named 'flaskthreads'
This error means the Python interpreter cannot find the `flaskthreads` library, most commonly because it hasn't been installed, or there's a typo in the import statement, or it's installed in a different Python environment than the one being used.
fix
Ensure the library is installed in your active Python environment using `pip install Flask-Threads`. Double-check your import statement for typos, e.g., `from flaskthreads import AppContextThread`.
AttributeError: 'Flask' object has no attribute '_get_current_object'
This error typically occurs when developers attempt to manually dereference a Flask context local proxy (like `current_app` or `request`) by calling `_get_current_object()` directly on a `Flask` application instance (e.g., `app._get_current_object()`) instead of the proxy itself (e.g., `current_app._get_current_object()`). The `_get_current_object()` method is part of the `LocalProxy` object (which `current_app` is), not the `Flask` application object directly.
fix
When you need the actual application object from within a context, use `current_app._get_current_object()`. When passing the application to a background thread, if not using `flask-threads`, ensure you pass the actual application instance (`app`) or handle the context explicitly within the thread using `app.app_context()`.
Upgrade
Version history
0.2.0latest on PyPI · released May 20, 2025
Audit
Dependencies
FlaskrequiredCore dependency for integration with Flask applications. Compatibility fixed for Flask >= 3.0.0.
Agent activity
12 hits · last 30 days
node
10
Amazon
1
Resources