Last active
February 17, 2023 20:29
-
-
Save Kilo59/40560fd4f84bed815158b9b79359c8bc to your computer and use it in GitHub Desktop.
Httpx Jokes
This file contains hidden or 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 time | |
import httpx | |
async def print_joke(r: httpx.Response): | |
r.raise_for_status() | |
await r.aread() | |
value = r.json()["value"] | |
print(f"id={value['id']} - {value['joke']}") | |
async def get_jokes(total: int): | |
async with httpx.AsyncClient( | |
base_url="http://api.icndb.com", | |
event_hooks={"response": [print_joke]}, | |
) as client_session: | |
tasks = [client_session.get("/jokes/random") for _ in range(0, total)] | |
await asyncio.gather(*tasks, return_exceptions=True) | |
if __name__ == "__main__": | |
start = time.time() | |
asyncio.run(get_jokes(50)) | |
end = time.time() | |
elapsed = end - start | |
print(f"Time elapsed: {elapsed:.4f} seconds") |
This file contains hidden or 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 time | |
import httpx | |
async def get_responses(total: int) -> list[httpx.Response]: | |
async with httpx.AsyncClient(base_url="http://api.icndb.com") as client_session: | |
tasks = [client_session.get("/jokes/random") for _ in range(0, total)] | |
return await asyncio.gather(*tasks) | |
async def print_jokes(total: int): | |
responses = await get_responses(total) | |
for i, r in enumerate(responses, start=1): | |
value = r.json()["value"] | |
print(f"{i} - id:{value['id']} {value['joke']}") | |
if __name__ == "__main__": | |
start = time.time() | |
asyncio.run(print_jokes(50)) | |
end = time.time() | |
elapsed = end - start | |
print(f"Time elapsed: {elapsed:.4f} seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Created in response to this blogpost
https://www.confessionsofadataguy.com/how-chuck-norris-proved-async-in-python-isnt-worthy/