Skip to main content

A helper library to work with threads within Flask applications.

Project description

Flask-Threads

Actions Status

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

$ pip install Flask-Threads

Examples

Threads

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 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)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Flask-Threads-0.1.0.tar.gz (4.1 kB view details)

Uploaded Source

File details

Details for the file Flask-Threads-0.1.0.tar.gz.

File metadata

  • Download URL: Flask-Threads-0.1.0.tar.gz
  • Upload date:
  • Size: 4.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.10.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.60.0 CPython/3.7.7

File hashes

Hashes for Flask-Threads-0.1.0.tar.gz
Algorithm Hash digest
SHA256 84df4e4d98f53d75aa403f52986d155db0319d0441ec7324259631bdcb512195
MD5 61a88f09e6f1674dfe015872a8247c56
BLAKE2b-256 762f82c24c44e2bf42af0c4353d7b910e67c41d553e6f586083339ea659d2385

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page