Skip to content

Instantly share code, notes, and snippets.

@pgjones
Last active March 6, 2018 02:50
Show Gist options
  • Save pgjones/1f2e873caedc6bc7bc1518606d9d79ac to your computer and use it in GitHub Desktop.
Save pgjones/1f2e873caedc6bc7bc1518606d9d79ac to your computer and use it in GitHub Desktop.
Understanding Asyncio Snippets
import asyncio
import aiohttp
from quart import Quart
app = Quart(__name__)
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
html = await response.read()
return {
"resp": response,
"html": html,
"url": url,
}
@app.route("/")
async def hello():
urls = [
"https://whatisjasongoldstein.com/",
"https://betheshoe.com/",
"https://theportfolioapp.com/",
"https://www.theatlantic.com/",
"https://www.example.org/",
"https://www.google.com/",
"https://badurl.whatisjasongoldstein.com/",
]
futures = [asyncio.ensure_future(fetch(url)) for url in urls]
output = ""
for future in futures:
try:
resp = await future
except Exception as error:
output += "<p><b>Error:</b> %s<p>" % error
continue
else:
output += "<p>%s loaded with a status %s and a length of %s</p>" % (
resp["url"], resp["resp"].status, len(resp["html"])
)
return output
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment