I am using fastapi with beanie as ODM and asyncio, 2 functions taking a lot of time so I decided to run these function in parallel, I tried thread but it's giving a function running in a different event loop error. I tried multiple solutions but they are not working. Some solutions suggested that threading should not be used with asyncio.
asyncio.to_thread(add_attack_shodan_results_to_scans_collection(cve_list_with_scan_id))
asyncio.to_thread(make_safe_dict_for_mongo_insertion_for_nmap(body.ip,inserted_id))
and other solutions are
asyncio.gather(
add_attack_shodan_results_to_scans_collection(cve_list_with_scan_id),
make_safe_dict_for_mongo_insertion_for_nmap(body.ip, inserted_id)
)
and
asyncio.run(add_attack_shodan_results_to_scans_collection(cve_list_with_scan_id))
asyncio.run(make_safe_dict_for_mongo_insertion_for_nmap(body.ip,inserted_id))
and
thrd1 = threading.Thread(target=make_thread_for_cve_calculation, args=(cve_list_with_scan_id))
thrd1.start()
thrd = threading.Thread(target=make_thread_for_nmap, args=(body.ip, inserted_id))
thrd.start()
and threading functions are
def make_thread_for_nmap(ip,scan_id):
logger.info(f'thread id:{threading.current_thread().ident}')
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(make_safe_dict_for_mongo_insertion_for_nmap(ip,scan_id))
loop.close()
def make_thread_for_cve_calculation(*calculate_cve):
logger.info(f'thread id:{threading.current_thread().ident}')
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(add_attack_shodan_results_to_scans_collection(calculate_cve))
loop.close()
What is the solution to run these function parallel or background? I also have checked the documentation but did not find any solution. Is there any way to run these function parallel without blocking other requests and what is the solution for "different event loop" error?