异步循环内嵌套函数的实现需求:使counter函数无需等待send_request响应,仅在HTTP响应到达时执行打印操作
Solution for Non-blocking Counter with Async HTTP Requests
Let's get your code working exactly as you need: where the counter function doesn't wait for send_request to complete, and the print operation only runs once the HTTP response is received. Here's the fixed implementation, plus breakdowns of the key changes:
Key Issues in the Original Code
- Spelling Error:
@app.incomeing_msgshould be@app.incoming_msg - Blocking HTTP Calls: The synchronous
requestslibrary will freeze your async event loop—we'll switch toaiohttp(Python's standard async HTTP library) - Unnecessary Await: Using
await asyncio.create_task(...)incountermakes it wait for the request to finish, which defeats your "no wait" requirement - Loop Function Misalignment: The original
loopdefinition andasyncio.run(loop())call don't fit the decorated handler pattern you're using
Fixed Code
import asyncio import random import aiohttp # Replace blocking requests with async aiohttp async def counter(i): print("Started counter ", i) # Create the request task WITHOUT awaiting it—counter exits immediately asyncio.create_task(send_request(random.randint(1, 10))) async def send_request(delay): print("Sending HTTP request with delay ", delay) await asyncio.sleep(delay) # Async HTTP call that won't block the event loop async with aiohttp.ClientSession() as session: async with session.get('http://example.com') as r: print(f"Got HTTP response with status {r.status} in time {delay}") # Fixed decorator spelling @app.incoming_msg(i) async def loop(i): # Launch counter task without waiting for it to finish asyncio.create_task(counter(i)) # If testing standalone (adjust based on your app's event loop setup): # asyncio.run(loop(some_test_id))
Critical Explanations
- Non-blocking Task Launch: In both
loopandcounter, we useasyncio.create_task()withoutawait. This lets the parent function exit right away while the task runs in the background—exactly what you need forcounterto not wait onsend_request. - Async HTTP with aiohttp: Unlike
requests,aiohttpmakes HTTP calls without blocking the entire event loop. Other tasks can run normally while we wait for the HTTP response. - Response-only Print: The status print in
send_requesttriggers only after the HTTP response is received.counterdoesn't hang around waiting for this—it just kicks off the request and moves on.
内容的提问来源于stack exchange,提问作者m.m h
相关产品推荐
相关产品推荐

