|
9 | 9 | from scrapy.http.headers import Headers
|
10 | 10 | from scrapy.settings import Settings
|
11 | 11 | from scrapy.utils.python import to_unicode
|
| 12 | +from twisted.internet import reactor |
12 | 13 | from twisted.internet.defer import Deferred
|
| 14 | +from twisted.python import failure |
13 | 15 | from w3lib.encoding import html_body_declared_encoding, http_content_type_encoding
|
14 | 16 |
|
15 | 17 |
|
@@ -115,24 +117,26 @@ class _ThreadedLoopAdapter:
|
115 | 117 | _stop_events: Dict[int, asyncio.Event] = {}
|
116 | 118 |
|
117 | 119 | @classmethod
|
118 |
| - async def _handle_coro(cls, coro, future) -> None: |
| 120 | + async def _handle_coro(cls, coro: Awaitable, dfd: Deferred) -> None: |
119 | 121 | try:
|
120 |
| - future.set_result(await coro) |
| 122 | + result = await coro |
121 | 123 | 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) |
123 | 127 |
|
124 | 128 | @classmethod
|
125 | 129 | async def _process_queue(cls) -> None:
|
126 | 130 | 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)) |
129 | 133 | cls._coro_queue.task_done()
|
130 | 134 |
|
131 | 135 | @classmethod
|
132 | 136 | 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 |
136 | 140 |
|
137 | 141 | @classmethod
|
138 | 142 | def start(cls, caller_id: int) -> None:
|
|
0 commit comments