Issue
I am working on a detection tool and I want to be able to control it over the web. The web service should support the tool to start and stop and modify the detection configuration. But I don't know how to make the service and the tool work in parallel, because the detection tool is constantly cycling through the detection.
I have some knowledge about web and asynchronous. But those methods I know are about "block and wait for all parallelizable tasks to finish at the end", but my probing tasks are supposed to be executed constantly after activation, which makes me confused.
I have written a small example to exemplify this:
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 {}
So I would like to know how to make this web service work in parallel with detect_task(). Thanks in advance for the help!
Solution
I have found the answer. Because fastAPI provides the BackgroundTasks function, all you have to do is to put the tasks in.
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 {}
The flags and detecors are simply global variables that are passed into the task as parameters.
Answered By - lxchx
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.