【问题标题】:Executing a function in parallel of fastapi与 fastapi 并行执行一个函数
【发布时间】:2021-02-04 08:00:08
【问题描述】:

我想执行一个与快速 api 并行运行的函数。

该功能基本上是从网络上获取数据并将其写入数据库,数据可能是百万条记录,可能需要超过 5 分钟。

API 接受数据并查询数据库并响应客户端。

我现在正在做的是

@app.on_event("startup")
async def startup_event():
    
    await Extractor().callit()
class Extractor:
    async def callit(self):
        # Insertion of the tor ips with the data models
        indicators = []
        indicators.clear()
        for ip in await scrap_web_ips():
            if ip == '':
                continue
            q_indicator = self.check_ip_status(ip)
            if q_indicator is None:
                indicator = Indicators(indicator=ip, tor=True,
                                       last_seen=get_current_date_in_iso(),
                                       first_seen=get_current_date_in_iso(),
                                       white_list=True if self.get_vt_stats(ip) == 0 else False)
                indicators.append(indicator)
            else:
                print("Updating the lastseen of the indicator.")
                q_indicator.last_seen = get_current_date_in_iso()
                q_indicator.tor = True
                self.session.commit()
    

         print(self.insert_data(indicators))

还有我的 API。

该函数正在阻止 api 调用。

我现在不知道如何处理。

【问题讨论】:

  • 我可以看到你在等待异步函数scrap_web_ips()。这个函数有 return 语句还是 yield 语句?如果它有一个 yield 语句,它就会变成一个异步生成器,然后这可能会在没有阻塞的情况下工作。但是,如果它有一个 return 语句,则整个代码块将在 for 循环开始循环之前等待变量形成。形成变量将不会阻塞,但随后循环每个“ip”将阻塞整个事物。
  • 更好的选择是使用 Celery 或一些轻量级的任务调度程序。一旦 FastAPI 开始启动一项工作并将其处理给 celery 或其他任务调度程序。现在开始,抓取和存储不是您的 FastAPI 责任数据..这种方法将有助于为您的用户提供比以前更好的服务..

标签: python-3.x async-await fastapi


【解决方案1】:

callit() 函数很可能实际上根本不是异步函数。你说它从网上收集一些东西并将其存储在数据库中。这两个动作是使用异步方法的主要候选者。这看起来像这样:

async def callit():
1  result = await get_from_web_async()
2  await store_in_db_async(result)

在第 1 行,它会在等待 get_from_web_async() 的结果时返回控制权,而在第 2 行,它会在将其存储在数据库中时再次返回控制权。

但是,如果没有你在 callit() 函数上的代码,这只是一个猜测 :)

编辑: 根据附加信息,工作原理是对scrap_web_ips() 的调用不返回异步生成器。因此,在循环之前等待整个结果。虽然在等待结果时调用没有阻塞,但它所使用的循环将完全阻塞。

【讨论】:

  • 好的,我正在通过调用它函数的实现来更新问题。
  • 好的,我已经更新了我的回复,如果对你有帮助,请告诉我
猜你喜欢
  • 2021-05-10
  • 1970-01-01
  • 2014-03-11
  • 2020-01-17
  • 2015-09-07
  • 1970-01-01
  • 2021-10-18
  • 2021-07-01
  • 1970-01-01
相关资源
最近更新 更多