Python-Flask-webservice中带回调的长异步计算

2024-05-29 07:28:46 发布

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

我想用python实现一个webservice,它的行为如下:

request to service: mysvc.com/doSomethingLong?callbackurl=http://callbackurl
response (immediate): 200 OK

(经过很长时间,python计算完成)

^{pr2}$

最好的方法是什么?在

我看到的大多数异步计算示例都不返回立即的“200ok”,而是等待响应,同时生成允许其他代码并行工作的控制。在


Tags: to方法comwebhttp示例responserequest
1条回答
网友
1楼 · 发布于 2024-05-29 07:28:46

在Flask应用程序中运行异步任务的一个解决方案是^{}。在

class concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=())

An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously.

initializer is an optional callable that is called at the start of each worker thread; initargs is a tuple of arguments passed to the initializer. Should initializer raise an exception, all currently pending jobs will raise a BrokenThreadPool, as well as any attempt to submit more jobs to the pool.

Changed in version 3.5: If max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor.

New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging.

Changed in version 3.7: Added the initializer and initargs arguments.

烧瓶示例

from concurrent.futures import ThreadPoolExecutor
from flask import Blueprint, request
from werkzeug.wrappers import BaseResponse as Response

client_session = Blueprint('client_session', __name__)


@client_session.route('/session-login', methods=['POST', 'PUT'])
def session_login():

    ...

    executor = ThreadPoolExecutor(5)
    executor.submit(my_long_running_task, my_task_param=42)

    # Return response immediately.
    return Response(
        response='{"status_text": "OK"}',
        status=200,
        mimetype='application/json; charset=UTF-8')

有关在烧瓶中使用ThreadPoolExecutor的预先配置的设计模式,请参见Flask-Executor。在



Example from Docs

^{pr2}$

相关问题 更多 >

    热门问题