如何使用Flask上下文concurrent.futures.ThreadPoolExecu

2024-09-27 21:33:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使多个请求异步并获得响应,我使用concurrent.futures来执行此操作,但是在我的函数中使用来自flaskcurrent_app,我总是得到这个错误:

RuntimeError: Working outside of application context.

我不知道怎么解决这个问题。谁能帮忙吗?在

以下是我的代码:

在运行.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在

^{pr2}$

Tags: frompyimportapphttpflaskgetcontext
2条回答

我也遇到过类似的问题同期期货带着烧瓶。我写了Flask-Executor作为同期期货来解决这个问题。对你来说,和这两个人一起工作可能更容易些。在

您应该在脚本中导入烧瓶实例。在应用程序上下文下使用current_app。在

import concurrent.futures
from your_application import your_app  # or create_app function to return a Flask instance
from flask import current_app
from http_calls import get_price, get_items

def init():
    with your_app.app_context():
        with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
            ...

相关问题 更多 >

    热门问题