python - 当收到请求时从脚本运行 Scrapy

标签 python scrapy fastapi

我有一个正在监听端点的FastAPI服务器,在收到任何发布请求后,它将使用Scrapy根据从中获取的数据来获取一些数据发布请求。

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings


class Request(BaseModel):
    someIDs: List[str]


process = CrawlerProcess(get_project_settings())

app = FastAPI()


@app.post("/")
def home(request: Request):
    process.crawl('rt_criteria', ids=request.someIDs)
    process.start()  # the script will block here until the crawling is finished
    return {"crawled": True}

# uvicorn main:app --reload

这段代码将按照我的预期第一次运行,但第二次,我会得到

twisted.internet.error.ReactorNotRestartable

错误:

process.start()

我应该在哪里写这个以及如何修复错误?

最佳答案

我使用 Background tasks 解决了这个问题在 FastAPI 中。

(我认为它在幕后使用多进程。)

from fastapi import FastAPI, BackgroundTasks

# *** Not changed codes ***

@app.post("/")
async def home(request: Request, bt: BackgroundTasks):
    process.crawl('rt_criteria', mid=request.movieIDs)
    # Changed line below using Background tasks
    bt.add_task(process.start, stop_after_crawl=False)
    return {"crawled": True}

# uvicorn main:app --reload

关于python - 当收到请求时从脚本运行 Scrapy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70066194/

相关文章:

带有 RotatingFileHandler 的 Python 3 记录器超过 maxBytes 限制

python - FastAPI 请求中的不可哈希类型

python - 仅本地理信息在 python 中可用时才运行

python - 使用适用于 Windows 的 Python 阻止/取消阻止端口可能吗?如何?

python - 尝试使用 django-subdomains 在我的 django urlpatterns 中查找循环引用?

linux - 如何使用 scrapy 命令动态创建 Feed Export 的文件名

python - 抓取亚马逊上的订单值(value),添加到相关抓取的产品中

python - Scrapy 重复结果

python - pydantic:对具有别名的字段使用 property.getter 装饰器

concurrency - gunicorn uvicorn worker.py 如何遵守 limit_concurrency 设置