Skip to content

Instantly share code, notes, and snippets.

@fabiocerqueira
Last active October 19, 2019 14:12
Show Gist options
  • Save fabiocerqueira/d48f6c48c56472def7a4b779834a7858 to your computer and use it in GitHub Desktop.
Save fabiocerqueira/d48f6c48c56472def7a4b779834a7858 to your computer and use it in GitHub Desktop.
Example sync function in a executor
import asyncio
from pprint import pprint
import requests
def io_block_socket_call(url):
resp = url, requests.get(url).status_code == 200
return resp
async def io_block_in_executor(url, task_id):
loop = asyncio.get_event_loop()
print("noblock pre", url, task_id)
resp = await loop.run_in_executor(None, io_block_socket_call, url)
print("noblock pos", url, task_id)
return resp
async def main():
loop = asyncio.get_running_loop()
urls = [
"https://www.google.com",
"https://www.pylestras.org",
"https://www.python.org",
"https://www.globo.com",
"https://www.uol.com.br",
"https://stackoverflow.com",
]
tasks = [io_block_in_executor(url, task_id) for task_id, url in enumerate(urls)]
result = await asyncio.gather(*tasks)
print("Results:")
pprint(result)
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment