Flask-Threads
A helper library to work with threads within Flask applications.
The main problem that you face trying to spin a background thread or running a
future in Flask app - is loosing the application context. The most common
scenario is to try to access flask.g object. Application context
is a thread local so you can not access it from another thread and Flask will
raise an exception if you would try to.
This library provides helper classes that allows you accessing the current application context from another thread.
Installation
$ pip install Flask-Threads
Examples
Threads
from flask import g
from flask import request
from flask import Flask
from flaskthreads import AppContextThread
app = Flask('my_app')
@app.route('/user')
def get_user():
g.user_id = request.headers.get('user-id')
t = AppContextThread(target=do_some_user_work_in_another_thread)
t.start()
t.join()
return 'ok'
def do_some_user_work_in_another_thread():
id = g.user_id
print(id)
Concurrent futures
from flask import g
from flask import request
from flask import Flask
from flaskthreads import ThreadPoolWithAppContextExecutor
app = Flask('my_app')
@app.route('/user')
def get_user():
g.user_id = request.headers.get('user-id')
with ThreadPoolWithAppContextExecutor(max_workers=2) as pool:
future = pool.submit(do_some_user_work_in_another_thread)
future.result()
return 'ok'
def do_some_user_work_in_another_thread():
id = g.user_id
print(id)
Metadata
Release files for Flask-Threads 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| flask_threads-0.2.0.tar.gz | 5.6 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| flask_threads-0.2.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 11.1 kB
Release files / flask_threads-0.2.0.tar.gz
| Download URL | flask_threads-0.2.0.tar.gz |
|---|---|
| Size | 5.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8dc6e8445cc8b97650f9c2b1a319b293a49e8f7e331b3d71dfe38a1f0b944fe5
|
|
BLAKE2b-256 checksum How to use checksums |
9639613f71271e9b69b277a8ebcc08fd5976e47ab4754ec15bc392b421f34e86
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.6
|
Release files / flask_threads-0.2.0-py3-none-any.whl
| Download URL | flask_threads-0.2.0-py3-none-any.whl |
|---|---|
| Size | 5.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1778c7c474efec6e97a6673b61631864c4142ed6db9187d0f2affeaca11eea44
|
|
BLAKE2b-256 checksum How to use checksums |
80c5be25f999a1dc4adde3228842114722efe9465c53e95be5c961f6b9e972d4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.11.6
|