【发布时间】: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