django - ReactorNotRestartable - 扭曲且困惑

标签 django web-applications scrapy twisted reactor

在您将我链接到与此相关的其他答案之前,请注意,我已阅读它们,但仍然有点困惑。好的,我们开始吧。

所以我正在 Django 中创建一个 Web 应用程序。我正在导入最新的 scrapy 库来抓取网站。我没有使用 celery (我对它知之甚少,但在与此相关的其他主题中看到过它)。

我们网站的 URL 之一/crawl/用于启动爬虫运行。这是我们网站中唯一需要使用 scrapy 的 url。这是访问 url 时调用的函数:

def crawl(request):
  configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'})
  runner = CrawlerRunner()

  d = runner.crawl(ReviewSpider)
  d.addBoth(lambda _: reactor.stop())
  reactor.run() # the script will block here until the crawling is finished

  return render(request, 'index.html')

您会注意到这是对其网站上的 scrapy 教程的改编。当服务器开始运行时第一次访问此 url 时,一切都会按预期进行。第二次以及更进一步,抛出 ReactorNotRestartable 异常。据我了解,当向已停止的 react 堆发出重新启动的命令时,会发生此异常,这是不可能的。

查看示例代码,我假设“runner = CrawlerRunner()”行将返回一个 ~new~ react 器,以便每次访问此 url 时使用。但我相信也许我对扭曲 react 堆的理解并不完全清楚。

每次访问此网址时,我将如何获取并运行一个新的 react 器?

非常感谢

最佳答案

一般来说,你不能拥有新的 react 堆。有一个全局性的。这显然是一个错误,也许将来会被纠正,但这就是目前的情况。

您也许可以使用Crochet管理在单独线程中运行的单个 react 器(在整个进程的生命周期内 - 不重复启动和停止)。

考虑the example from the Crochet docs :

#!/usr/bin/python
"""
Do a DNS lookup using Twisted's APIs.
"""
from __future__ import print_function

# The Twisted code we'll be using:
from twisted.names import client

from crochet import setup, wait_for
setup()


# Crochet layer, wrapping Twisted's DNS library in a blocking call.
@wait_for(timeout=5.0)
def gethostbyname(name):
    """Lookup the IP of a given hostname.

    Unlike socket.gethostbyname() which can take an arbitrary amount of time
    to finish, this function will raise crochet.TimeoutError if more than 5
    seconds elapse without an answer being received.
    """
    d = client.lookupAddress(name)
    d.addCallback(lambda result: result[0][0].payload.dottedQuad())
    return d


if __name__ == '__main__':
    # Application code using the public API - notice it works in a normal
    # blocking manner, with no event loop visible:
    import sys
    name = sys.argv[1]
    ip = gethostbyname(name)
    print(name, "->", ip)

这为您提供了一个使用 Twisted API 实现的阻塞 gethostbyname 函数。该实现使用twisted.names.client,它仅依赖于能够导入全局 react 器。

请注意,没有 reactor.runreactor.stop 调用 - 只有 Crochet setup 调用。

关于django - ReactorNotRestartable - 扭曲且困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44788051/

相关文章:

python - 将 Scrapy 与 Django 集成 : How to

django - 更改 Django 表单值

python - 给定日期后的 DatetimeField 过滤器

exception - scrapy未处理的异常

Django Imagefield 无法通过 ModelForm 正常工作

php - 无法使用 php 读取或写入数据库

tomcat - 一旦我的 Web 应用程序成功部署到 Tomcat 中,如何获得通知?

iOS:通过网络应用程序播放 RTSP 播放器

python - 如何让 Selenium 与 Scrapy 并行运行?

python - 使用中间件防止scrapy重复访问网站