You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

异步循环内嵌套函数的实现需求:使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_msg should be @app.incoming_msg
  • Blocking HTTP Calls: The synchronous requests library will freeze your async event loop—we'll switch to aiohttp (Python's standard async HTTP library)
  • Unnecessary Await: Using await asyncio.create_task(...) in counter makes it wait for the request to finish, which defeats your "no wait" requirement
  • Loop Function Misalignment: The original loop definition and asyncio.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

  1. Non-blocking Task Launch: In both loop and counter, we use asyncio.create_task() without await. This lets the parent function exit right away while the task runs in the background—exactly what you need for counter to not wait on send_request.
  2. Async HTTP with aiohttp: Unlike requests, aiohttp makes HTTP calls without blocking the entire event loop. Other tasks can run normally while we wait for the HTTP response.
  3. Response-only Print: The status print in send_request triggers only after the HTTP response is received. counter doesn't hang around waiting for this—it just kicks off the request and moves on.

内容的提问来源于stack exchange,提问作者m.m h

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 15:18:14