Created
November 25, 2018 06:39
-
-
Save komuw/010c5e552ec939a2d8c0540a75c6ad8d to your computer and use it in GitHub Desktop.
calling blocking code in async code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
python blocking_async.py