Skip to content

Instantly share code, notes, and snippets.

@komuw
Created November 25, 2018 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komuw/010c5e552ec939a2d8c0540a75c6ad8d to your computer and use it in GitHub Desktop.
Save komuw/010c5e552ec939a2d8c0540a75c6ad8d to your computer and use it in GitHub Desktop.
calling blocking code in async code
import asyncio
import requests
import concurrent
import functools
loop = asyncio.get_event_loop()
def reqq(timeout):
url = "https://httpbin.org/delay/14"
r = requests.get(url, timeout=timeout)
print("\t\n ress")
print(r)
return r
async def make():
timeout = 56
# running blocking code in a python3 async world:
# 1. https://docs.python.org/3/library/asyncio-dev.html#running-blocking-code
# 2. https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor
with concurrent.futures.ThreadPoolExecutor(
thread_name_prefix="naz-rabbitmq-thread-pool"
) as executor:
result = await loop.run_in_executor(executor, functools.partial(reqq, timeout=timeout))
print("resukt")
print(result)
async def forever():
while True:
print("forever1")
await asyncio.sleep(3, loop=loop)
print("forever2")
tasks = asyncio.gather(forever(), make())
loop.run_until_complete(tasks)
@komuw
Copy link
Author

komuw commented Nov 25, 2018

python blocking_async.py

forever1
forever2
forever1
forever2
forever1
forever2
forever1
	
 ress
<Response [200]>
resukt
<Response [200]>
forever2
forever1
forever2
forever1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment