Twisted provides wrapping native coroutines(coroutines using async/await). Using ensureDeferred, we can wrap a coroutine and get its equivalent deferred. How to wrap an asynchronous generator (available in Python 3.6), so that we get a deferred ?
Trying to wrap an asynchronous object returns following error:
File "/home/yash/Scrapy/vnv/lib/python3.6/site-packages/Twisted-17.9.0-py3.6-linux-x86_64.egg/twisted/internet/defer.py", line 915, in ensureDeferred
raise ValueError("%r is not a coroutine or a Deferred" % (coro,))
ValueError: is not a coroutine or a Deferred
EDIT: I have provided a sample code where the logic required is demonstrated,and the corresponding error occuring:
from twisted.internet import reactor, defer
import asyncio
async def start_request():
urls = ['https://example.com/page/1',
'https://example.com/page/2',
'https://example.com/page/3']
async for url in urls:
yield url
await asyncio.sleep(2)
async def after_request():
await asyncio.sleep(3)
print("Completed the work")
deferred = ensureDeferred(start_request())
deferred.addCallback(after_request())
print("reactor has started")
reactor.run()
Error Traceback:
Traceback (most recent call last):
File "req2.py", line 20, in <module>
deferred = defer.ensureDeferred(start_request())
File "/home/yash/Scrapy/vnv/lib/python3.6/site-packages/Twisted-
17.9.0-py3.6-linux-x86_64.egg/twisted/internet/defer.py", line 915, in
ensureDeferred
raise ValueError("%r is not a coroutine or a Deferred" % (coro,))
ValueError: <async_generator object start_request at 0x7febb282cf50>
is not a coroutine or a Deferred