Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sintezcs/flask-threads
A helper library to work with threads in Flask
https://github.com/sintezcs/flask-threads
flask multithreading python
Last synced: 3 months ago
JSON representation
A helper library to work with threads in Flask
- Host: GitHub
- URL: https://github.com/sintezcs/flask-threads
- Owner: sintezcs
- License: mit
- Created: 2019-09-02T15:45:13.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2021-04-06T11:38:19.000Z (almost 4 years ago)
- Last Synced: 2024-09-28T18:41:14.906Z (3 months ago)
- Topics: flask, multithreading, python
- Language: Python
- Size: 34.2 KB
- Stars: 30
- Watchers: 2
- Forks: 5
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## Flask-Threads
[![Actions Status](https://github.com/sintezcs/flask-threads/workflows/GitHub%20Build/badge.svg)](https://github.com/sintezcs/flask-threads/actions)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.**Warning! Alpha-version, use at your own risk.**
### Installation
```bash
$ pip install Flask-Threads
```### Examples
#### Threads
```python
from flask import g
from flask import request
from flask import Flask
from flaskthreads import AppContextThreadapp = 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
```python
from flask import g
from flask import request
from flask import Flask
from flaskthreads import ThreadPoolWithAppContextExecutorapp = 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)
```