Skip to content

Instantly share code, notes, and snippets.

@Kilo59
Last active February 17, 2023 20:29
Show Gist options
  • Save Kilo59/40560fd4f84bed815158b9b79359c8bc to your computer and use it in GitHub Desktop.
Save Kilo59/40560fd4f84bed815158b9b79359c8bc to your computer and use it in GitHub Desktop.
Httpx Jokes
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")
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")
@Kilo59
Copy link
Author

Kilo59 commented Feb 17, 2023

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