concurrency_client.py 637 B

1234567891011121314151617181920
  1. """先启动 uvicorn,再运行 python concurrency_client.py。"""
  2. import asyncio
  3. from time import perf_counter
  4. import httpx
  5. async def main():
  6. async with httpx.AsyncClient(base_url="http://127.0.0.1:8000", timeout=10) as client:
  7. started = perf_counter()
  8. responses = await asyncio.gather(*[client.get("/slow?delay=1") for _ in range(4)])
  9. for index, response in enumerate(responses, start=1):
  10. response.raise_for_status()
  11. print(f"请求 {index}: {response.json()}")
  12. print(f"总耗时: {perf_counter() - started:.2f} 秒")
  13. if __name__ == "__main__":
  14. asyncio.run(main())