【问题标题】:Run Scrapy from a script when it gets a request收到请求时从脚本运行 Scrapy
【发布时间】:2021-11-22 13:03:05
【问题描述】:

我有一个正在监听端点的 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()

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

【问题讨论】:

    标签: python scrapy fastapi


    【解决方案1】:

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

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

    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
    

    【讨论】:

      猜你喜欢
      • 2017-05-16
      • 2020-09-26
      • 1970-01-01
      • 2014-03-06
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      相关资源
      最近更新 更多