Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Use the asyncio reactor's loop when no loop is running. (#8325)

Andrey Rakhmatullindb2404bb8691
diff --git a/scrapy/utils/asyncio.py b/scrapy/utils/asyncio.py
index 7fd4f7531..beb4a4810 100644
--- a/scrapy/utils/asyncio.py
+++ b/scrapy/utils/asyncio.py
@@ -104,6 +104,33 @@ def is_asyncio_available() -> bool:
return _is_asyncio_reactor_installed()
+def _get_running_or_installed_loop() -> asyncio.AbstractEventLoop:
+ """Return the event loop to use, even if it isn't running yet.
+
+ This is the loop running in the current thread or, if there is none, the
+ loop of the installed asyncio Twisted reactor, which exists before the
+ reactor starts. If there is neither, raise :exc:`RuntimeError`.
+
+ Unlike :func:`asyncio.get_event_loop`, this doesn't use the current event
+ loop of the calling thread, which can be a different loop or none.
+ """
+ try:
+ return asyncio.get_running_loop()
+ except RuntimeError:
+ pass
+
+ if not is_reactor_installed() or not _is_asyncio_reactor_installed():
+ raise RuntimeError(
+ "There is no running asyncio event loop and no installed asyncio"
+ " Twisted reactor."
+ )
+
+ from twisted.internet import reactor
+
+ loop: asyncio.AbstractEventLoop = reactor._asyncioEventloop
+ return loop
+
+
async def _parallel_asyncio(
iterable: Iterable[_T] | AsyncIterator[_T],
count: int,
@@ -183,7 +210,7 @@ class AsyncioLoopingCall(Generic[_P, _T]):
self._start_time = start_time = time.monotonic()
if now:
self._call()
- loop = asyncio.get_event_loop()
+ loop = _get_running_or_installed_loop()
self._task = loop.create_task(self._loop(start_time))
def _next_boundary(self, boundary: float) -> float:
@@ -259,7 +286,7 @@ def call_later(
.. versionadded:: 2.14.0
"""
if is_asyncio_available():
- loop = asyncio.get_event_loop()
+ loop = _get_running_or_installed_loop()
return CallLaterResult.from_asyncio(loop.call_later(delay, func, *args))
from twisted.internet import reactor
diff --git a/scrapy/utils/defer.py b/scrapy/utils/defer.py
index 70609aee6..d8eedf306 100644
--- a/scrapy/utils/defer.py
+++ b/scrapy/utils/defer.py
@@ -30,7 +30,11 @@ from twisted.internet.task import Cooperator
from twisted.python import failure
from scrapy.exceptions import ScrapyDeprecationWarning
-from scrapy.utils.asyncio import is_asyncio_available, sleep
+from scrapy.utils.asyncio import (
+ _get_running_or_installed_loop,
+ is_asyncio_available,
+ sleep,
+)
from scrapy.utils.python import global_object_name
if TYPE_CHECKING:
@@ -493,7 +497,9 @@ def deferred_from_coro(o: Awaitable[_T] | _T2) -> Deferred[_T] | _T2:
# that use asyncio, e.g. "await asyncio.sleep(1)"
return Deferred.fromCoroutine(cast("Coroutine[Deferred[Any], Any, _T]", o))
# wrapping the coroutine into a Future and then into a Deferred, this requires AsyncioSelectorReactor
- return Deferred.fromFuture(asyncio.ensure_future(o))
+ return Deferred.fromFuture(
+ asyncio.ensure_future(o, loop=_get_running_or_installed_loop())
+ )
return o
@@ -590,7 +596,7 @@ def deferred_to_future(d: Deferred[_T]) -> Future[_T]:
"deferred_to_future() requires an installed asyncio reactor"
" or a running asyncio event loop."
)
- return d.asFuture(asyncio.get_event_loop())
+ return d.asFuture(_get_running_or_installed_loop())
def maybe_deferred_to_future(d: Deferred[_T]) -> Deferred[_T] | Future[_T]:
diff --git a/tests/CrawlerProcess/asyncio_enabled_reactor_loop_not_current.py b/tests/CrawlerProcess/asyncio_enabled_reactor_loop_not_current.py
new file mode 100644
index 000000000..e4d8336b2
--- /dev/null
+++ b/tests/CrawlerProcess/asyncio_enabled_reactor_loop_not_current.py
@@ -0,0 +1,22 @@
+import asyncio
+
+from twisted.internet import asyncioreactor
+
+import scrapy
+from scrapy.crawler import CrawlerProcess
+
+# Twisted doesn't make a loop passed to it the current event loop.
+asyncioreactor.install(asyncio.SelectorEventLoop())
+
+
+class NoRequestsSpider(scrapy.Spider):
+ name = "no_request"
+
+ async def start(self):
+ return
+ yield
+
+
+process = CrawlerProcess()
+process.crawl(NoRequestsSpider)
+process.start()
diff --git a/tests/test_crawler_subprocess.py b/tests/test_crawler_subprocess.py
index 6c03168e6..057c03f35 100644
--- a/tests/test_crawler_subprocess.py
+++ b/tests/test_crawler_subprocess.py
@@ -371,6 +371,11 @@ class TestCrawlerProcessSubprocess(TestCrawlerProcessSubprocessBase):
in log
)
+ def test_asyncio_enabled_reactor_loop_not_current(self) -> None:
+ log = self.run_script("asyncio_enabled_reactor_loop_not_current.py")
+ assert "Spider closed (finished)" in log
+ assert "ERROR: " not in log
+
class TestAsyncCrawlerProcessSubprocess(TestCrawlerProcessSubprocessBase):
@property
diff --git a/tests/test_utils_asyncio.py b/tests/test_utils_asyncio.py
index 4fd53bd8c..2e29d5a19 100644
--- a/tests/test_utils_asyncio.py
+++ b/tests/test_utils_asyncio.py
@@ -328,3 +328,10 @@ class TestAsyncioLoopingCall:
await _wait_for(lambda: len(calls) >= 3)
looping_call.stop()
assert calls == [1, 4, 5]
+
+
[email protected]_not_asyncio
+def test_looping_call_no_asyncio() -> None:
+ looping_call = AsyncioLoopingCall(lambda: None)
+ with pytest.raises(RuntimeError, match="no running asyncio event loop"):
+ looping_call.start(1, now=False)
diff --git a/tests/test_utils_defer.py b/tests/test_utils_defer.py
index 8c63de927..87b523b37 100644
--- a/tests/test_utils_defer.py
+++ b/tests/test_utils_defer.py
@@ -444,6 +444,17 @@ class TestDeferredToFuture:
future_result = await result
assert future_result == 42
+ @pytest.mark.requires_reactor
+ @coroutine_test
+ async def test_thread_without_loop(self):
+ # No loop runs in the other thread, so the future gets the loop of the
+ # installed reactor.
+ d: Deferred[int] = Deferred()
+ result = await asyncio.to_thread(deferred_to_future, d)
+ assert result.get_loop() is asyncio.get_running_loop()
+ d.callback(42)
+ assert await result == 42
+
@pytest.mark.only_not_asyncio
class TestDeferredToFutureNotAsyncio: