Debug missing output in Python async HTTP flow
MillenniumSoftware Engineer · OnsiteLast updated
This question evaluates understanding of asynchronous programming in Python, including event loop management and async I/O semantics, and is categorized under Software Engineering Fundamentals with a focus on practical application of concurrency concepts.
You are given a Python program intended to call two HTTP APIs in order, process the returned JSON, and finally print the computed result. However, when you run the program, it exits without printing the expected output.
Assume an async HTTP client (e.g., aiohttp) is used.
Code (simplified)
import asyncio
import aiohttp
async def fetch_json(session, url):
async with session.get(url) as resp:
return await resp.json()
async def pipeline():
async with aiohttp.ClientSession() as session:
a = fetch_json(session, "https://api.example.com/a")
b = fetch_json(session, "https://api.example.com/b")
result = (await a)["value"] + (await b)["value"]
print("result:", result)
def main():
pipeline()
if __name__ == "__main__":
main()
Tasks
- Explain why the program does not print anything (or prints inconsistently).
- Show how you would fix it so the API calls actually execute and
printreliably runs. - As a follow-up: if the intent is to run both HTTP calls concurrently, what is the idiomatic way to do that, and what pitfalls should you watch for (e.g., cancellation, exceptions, and program exit)?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.