简体   繁体   English

httpx - 从动态列表发送多个请求

[英]httpx - send multiple requests from dynamic list

I would like to send multiple request at once to the API.我想一次向 API 发送多个请求。 But I do not know how to trigger the requests because part of the URL is loaded from dynamic list which can have different length every time.但我不知道如何触发请求,因为 URL 的一部分是从动态列表加载的,每次都可以有不同的长度。

Right now I am looping through the list and sending the request one by one but that is kinda slow.现在我正在遍历列表并一一发送请求,但这有点慢。

for url_param in parameters:
    r = httpx.get(f"http://my-api/{url_param}")

Is there any way to trigger all the requests at once with httpx and asyncio?有没有办法用 httpx 和 asyncio 一次触发所有请求?

Load all the request in an array and send them together in an async client session将所有请求加载到数组中,并将它们一起发送到异步客户端 session

import asyncio
import httpx

async def do_tasks():
    async with httpx.AsyncClient() as client:
        tasks = [httpx.get(f"http://my-api/{url_param}") for url_param in parameters]
        result = await asyncio.gather(*tasks)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM