简体   繁体   English

httpx:如何从收集的请求任务中访问特定响应?

[英]httpx: How to access specific responses from gathered request tasks?

I want to use HTTPX (within FastAPI, if that matters) to make asynchronous http requests to an outside API and store the responses as individual variables for processing in slightly different ways depending on which URL was fetched.我想使用 HTTPX(在 FastAPI 内,如果这很重要)向外部 API 发出异步 http 请求,并将响应存储为单独的变量,以便根据提取的 ZE6B391A8D2C4D45902A23A8B63 以稍微不同的方式进行处理。 I'm modifying the code from this StackOverflow answer.我正在修改StackOverflow 答案中的代码。

import asyncio
import httpx

async def perform_request(client, url):
    response = await client.get(url)
    return response.text

async def gather_tasks(*urls):
    async with httpx.AsyncClient() as client:
        tasks = [perform_request(client, url) for url in urls]
        result = await asyncio.gather(*tasks)
        return result

async def f():
    url1 = "https://api.com/object=562"
    url2 = "https://api.com/object=383"
    url3 = "https://api.com/object=167"
    url4 = "https://api.com/object=884"
    result = await gather_tasks(url1, url2, url3, url4)
    # print(result[0])
    # print(result[1])
    # DO THINGS WITH url2, SOMETHING ELSE WITH url4, ETC.

if __name__ == '__main__':
    asyncio.run(f())

What's the best way to access the individual responses?访问个人回复的最佳方式是什么? (If I use result[n] I wouldn't know which response I'm working with.) (如果我使用 result[n] 我不知道我正在使用哪个响应。)

And I'm pretty new to httpx and async operations in general so please share if you have any suggestions for how to achieve it in a better way.而且我对 httpx 和一般的异步操作还很陌生,所以如果您对如何以更好的方式实现它有任何建议,请分享。

Regardless of AsyncIO, I would probably put the logic inside gather_tasks .不管 AsyncIO 是什么,我可能会将逻辑放在gather_tasks中。 There you know the response, and you can define all the if else logic you want to proceed with the right path.在那里你知道响应,你可以定义所有你想要继续正确路径的if else逻辑。

In my opinion you have two options:在我看来,你有两个选择:


1 - Process the request right away 1 - 立即处理请求

In this case f would only initialize the urls and trigger the processing, everything else would happen inside gather_tasks .在这种情况下, f只会初始化 url 并触发处理,其他一切都会发生在gather_tasks中。

2 - "Enrich" the response 2 - “丰富”响应

In gather_tasks you can understand which kind of operation to do next, and "attach" to the response some sort of code to define it.gather_tasks中,您可以了解下一步要执行哪种操作,并将某种代码“附加”到响应中来定义它。 For example, you could return a dict with two keys: response and operation.例如,您可以返回一个带有两个键的 dict:响应和操作。 This would be the most explicit way of doing this, but you could also use a list or a tuple, you just need to know where the response and the "next step code" is within them.这将是最明确的方式,但您也可以使用列表或元组,您只需要知道响应和“下一步代码”在其中的位置。

This is useful if the further processing must happen later instead of right away.如果必须稍后而不是立即进行进一步处理,这将很有用。


Makes sense?说得通?

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

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