我正在开发一个检测工具,我希望能够在网络上控制它。web服务应支持工具的启动和停止以及修改检测配置。但我不知道如何使服务和工具并行工作,因为检测工具不断地在检测过程中循环。
我有一些关于网络和异步的知识。但我知道的那些方法是“阻塞并等待所有可并行任务在结束时完成”,但我的探测任务应该在激活后不断执行,这让我感到困惑。
我已经写了一个小例子来说明这一点:
from typing import Optional, List
from fastapi import FastAPI, Query
from pydantic import BaseModel
config = {}
should_detecting = False
is_detecting = False
config_changed = False
def detect_task():
global is_detecting
global config_changed
while should_detecting:
is_detecting = True
result = do_time_consuming_detect(config)
if should_detecting and not config_changed:
send(result)
config_changed = False
is_detecting = False
@app.get(root_route + "/detect")
def do_detect(start_flag: int):
global should_detecting
if start_flag == 1 and is_detecting != True:
should_detecting = True
execute_asynchronously(detect_task)
elif start_flag == 0:
should_detecting = False
return {}
@app.get(root_route + "/update_config")
def update_config(new_config: dict):
global config_changed
config_changed = True
config.update(new_config)
return {}所以我想知道如何使这个web服务与detect_task()并行工作。提前感谢您的帮助!
发布于 2021-06-26 19:10:02
我已经找到了答案。因为fastAPI提供了BackgroundTasks函数,所以您需要做的就是将任务放入其中。
def detect(flags, ips):
flags['is_detecting'] = True
while flags['should_detect']:
do_some_detect()
flags['is_detecting'] = False
@app.get(root_route + "/detect")
def read_detect(start_flag: int, background_tasks: BackgroundTasks):
if start_flag == 1 and not flags['is_detecting']:
flags['should_detect'] = True
background_tasks.add_task(detect, flags, detecors)
elif start_flag == 0:
flags['should_detect'] = False
return {}标志和检测器只是作为参数传递到任务中的全局变量。
https://stackoverflow.com/questions/68118109
复制相似问题