我使用 fastapi 和 beanie 作为 ODM 和 asyncio,这两个函数需要花费很多时间,所以我决定并行运行这些函数,我尝试了线程,但它给出了 在不同事件循环中运行的函数错误。我尝试了多种解决方案,但它们不起作用。一些解决方案建议线程不应与 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))
其他解决方案是
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)
)
和
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))
和
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()
线程函数是
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()
并行或后台运行这些函数的解决方案是什么?我也检查了文档,但没有找到任何解决方案。有什么方法可以并行运行这些函数而不阻塞其他请求,“不同事件循环”错误的解决方案是什么?