Issue
I just learned async with python 3.5 yesterday.
here is what I want to accomplish today.
import asyncio
import time
import requests
async def foo():
"""Some Long Running Taks"""
requests.get("http://stackoverflow.com/questions/41301031/asyncio-on-long-running-task")
print("foo")
async def bar():
"""Some Quick Task"""
print("bar")
while True:
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(foo(), bar()))
loop.close()
time.sleep(2)
#Expected output
"""
>>>bar
>>>bar
>>>bar
>>>bar
>>>bar
>>>foo
and so on
"""
Is this possible using python async/await?
Solution
You have a few issues in your code:
requests does not support asyncio, use aiohttp instead.
Your couroutines will run only when the loop is running: Call
loop.run_until_complete()
only once in your code, and schedule many (short or long) tasks usingawait
(orasycio.ensure_future()
orloop.create_task()
).
Here is an example doing something similar to what you were trying to do:
# make sure to run `pip install aiohttp` first!!!
import asyncio
import aiohttp
async def slow_fetch(delay):
url = "http://httpbin.org/delay/{}".format(delay)
print("Getting ", url)
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
text = await resp.text()
print("Got {}, {} chars".format(url, len(text)))
async def quick_loop():
print("enter quick_loop")
for i in range(10):
await asyncio.sleep(1)
print("quick_loop", i)
print("exit quick_loop")
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
slow_fetch(3),
slow_fetch(4),
quick_loop(),
))
loop.close()
Answered By - Udi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.