twisted.internet.defer.ensureDeferred(coro) function documentationtwisted.internet.defer
View Source
Schedule the execution of a coroutine that awaits/yields from Deferreds,
wrapping it in a Deferred that
will fire on success/failure of the coroutine. If a Deferred is passed to
this function, it will be returned directly (mimicing
asyncio's ensure_future function).
Coroutine functions return a coroutine object, similar to how generators work. This function turns that coroutine into a Deferred, meaning that it can be used in regular Twisted code. For example:
import treq
from twisted.internet.defer import ensureDeferred
from twisted.internet.task import react
async def crawl(pages):
results = {}
for page in pages:
results[page] = await treq.content(await treq.get(page))
return results
def main(reactor):
pages = [
"http://localhost:8080"
]
d = ensureDeferred(crawl(pages))
d.addCallback(print)
return d
react(main)
| Parameters | coro | The coroutine object to schedule, or a Deferred. (type: A Python 3.5+ async def coroutine, a Python 3.4+
yield from using types.GeneratorType,
or a Deferred.) |
| Returns | (type: Deferred) | |