Skip to content

Commit bf141e4

Browse files
committed
Replace scrapy.utils.defer.deferred_from_coro
1 parent 9932241 commit bf141e4

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

scrapy_playwright/_utils.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
from scrapy.http.headers import Headers
1010
from scrapy.settings import Settings
1111
from scrapy.utils.python import to_unicode
12+
from twisted.internet import reactor
1213
from twisted.internet.defer import Deferred
14+
from twisted.python import failure
1315
from w3lib.encoding import html_body_declared_encoding, http_content_type_encoding
1416

1517

@@ -115,24 +117,26 @@ class _ThreadedLoopAdapter:
115117
_stop_events: Dict[int, asyncio.Event] = {}
116118

117119
@classmethod
118-
async def _handle_coro(cls, coro, future) -> None:
120+
async def _handle_coro(cls, coro: Awaitable, dfd: Deferred) -> None:
119121
try:
120-
future.set_result(await coro)
122+
result = await coro
121123
except Exception as exc:
122-
future.set_exception(exc)
124+
reactor.callFromThread(dfd.errback, failure.Failure(exc))
125+
else:
126+
reactor.callFromThread(dfd.callback, result)
123127

124128
@classmethod
125129
async def _process_queue(cls) -> None:
126130
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))
131+
coro, dfd = await cls._coro_queue.get()
132+
asyncio.create_task(cls._handle_coro(coro, dfd))
129133
cls._coro_queue.task_done()
130134

131135
@classmethod
132136
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)
137+
dfd: Deferred = Deferred()
138+
asyncio.run_coroutine_threadsafe(cls._coro_queue.put((coro, dfd)), cls._loop)
139+
return dfd
136140

137141
@classmethod
138142
def start(cls, caller_id: int) -> None:

0 commit comments

Comments
 (0)