Skip to content

Commit 267ab08

Browse files
authored
Replace scrapy.utils.defer.deferred_from_coro (#351)
* Replace scrapy.utils.defer.deferred_from_coro * Pylint: ignore reactor class * Delay reactor import
1 parent 9932241 commit 267ab08

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

pylintrc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,6 @@ disable=
2020
[FORMAT]
2121
expected-line-ending-format=LF
2222
max-line-length=99
23+
24+
[MASTER]
25+
ignored-classes=twisted.internet.reactor

scrapy_playwright/_utils.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from scrapy.settings import Settings
1111
from scrapy.utils.python import to_unicode
1212
from twisted.internet.defer import Deferred
13+
from twisted.python import failure
1314
from w3lib.encoding import html_body_declared_encoding, http_content_type_encoding
1415

1516

@@ -115,24 +116,28 @@ class _ThreadedLoopAdapter:
115116
_stop_events: Dict[int, asyncio.Event] = {}
116117

117118
@classmethod
118-
async def _handle_coro(cls, coro, future) -> None:
119+
async def _handle_coro(cls, coro: Awaitable, dfd: Deferred) -> None:
120+
from twisted.internet import reactor
121+
119122
try:
120-
future.set_result(await coro)
123+
result = await coro
121124
except Exception as exc:
122-
future.set_exception(exc)
125+
reactor.callFromThread(dfd.errback, failure.Failure(exc))
126+
else:
127+
reactor.callFromThread(dfd.callback, result)
123128

124129
@classmethod
125130
async def _process_queue(cls) -> None:
126131
while any(not ev.is_set() for ev in cls._stop_events.values()):
127-
coro, future = await cls._coro_queue.get()
128-
asyncio.create_task(cls._handle_coro(coro, future))
132+
coro, dfd = await cls._coro_queue.get()
133+
asyncio.create_task(cls._handle_coro(coro, dfd))
129134
cls._coro_queue.task_done()
130135

131136
@classmethod
132137
def _deferred_from_coro(cls, coro) -> Deferred:
133-
future: asyncio.Future = asyncio.Future()
134-
asyncio.run_coroutine_threadsafe(cls._coro_queue.put((coro, future)), cls._loop)
135-
return scrapy.utils.defer.deferred_from_coro(future)
138+
dfd: Deferred = Deferred()
139+
asyncio.run_coroutine_threadsafe(cls._coro_queue.put((coro, dfd)), cls._loop)
140+
return dfd
136141

137142
@classmethod
138143
def start(cls, caller_id: int) -> None:

0 commit comments

Comments
 (0)