Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use flask context with concurrent.futures.ThreadPoolExecutor

I'm trying to make multiple requests async and get response back, I'm using concurrent.futures to do this, but inside my function using current_app which from flask and I always got this error:

RuntimeError: Working outside of application context.

I don't know how to resolve this. Can anyone please help?

Below are my code:

run.py:

import concurrent.futures
from flask import current_app
from http_calls import get_price, get_items

def init():
    with current_app._get_current_object().test_request_context():
        with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
            futs = []
            futs.append(executor.submit(get_price))
            futs.append(executor.submit(get_items))

            print([fut.result() for fut in concurrent.futures.as_completed(futs)])

init()

http_calls.py

from flask import current_app

def get_price():
    url = current_app.config['get_price_url']
    return requests.get(url).json()

def get_items():
    url = current_app.config['get_items_url']
    return requests.get(url).json()
like image 747
Thanh Nguyen Avatar asked Apr 29 '18 07:04

Thanh Nguyen


People also ask

What is concurrent futures ThreadPoolExecutor?

The concurrent. futures module provides a high-level interface for asynchronously executing callables. The asynchronous execution can be performed with threads, using ThreadPoolExecutor , or separate processes, using ProcessPoolExecutor .

Is ThreadPoolExecutor thread safe python?

ThreadPoolExecutor Thread-Safety Although the ThreadPoolExecutor uses threads internally, you do not need to work with threads directly in order to execute tasks and get results. Nevertheless, when accessing resources or critical sections, thread-safety may be a concern.

Which module can be used to implement concurrency in Python 3?

Another solution, than using of explicit locks, is to use a data structure that supports concurrent access. For example, we can use the queue module, which provides thread-safe queues. We can also use multiprocessing. JoinableQueue classes for multiprocessing-based concurrency.


1 Answers

I was running into similar issues around using concurrent.futures with Flask. I wrote Flask-Executor as a Flask-friendly wrapper for concurrent.futures to solve this problem. It may be an easier way for you to work with these two together.

like image 64
daveruinseverything Avatar answered Sep 23 '22 23:09

daveruinseverything