1

I have the below piece of code

async def get_data(uuid):
    async with sema, httpx.AsyncClient(
        base_url=udi_data_url, params=params
    ) as udi_client:
        udi_result = udi_client.get(f"/{uuid}")
    async with sema, httpx.AsyncClient(
        base_url=manufacturer_data_url, params=params
    ) as client:
        manufacturing_result = client.get(f"/{uuid}")
    result1, result2 = await asyncio.gather(udi_result, manufacturing_result)
    print(result1, result2)


async def main():
    await get_data(uuid)


asyncio.run(main())

How do I keep the client connections open as i understand the moment i reach this line result1, result2 = await asyncio.gather(udi_result, manufacturing_result)

I know that i can do something like

udi_result = await udi_client.get(f"/{uuid}")
and
manufacturing_result = await client.get(f"/{uuid}")

But that's not what I want to do.

I am out of the context and thus I am getting an error.

jhon.smith
  • 1,963
  • 6
  • 30
  • 56
  • 1
    You need to open the two `async` contexts, `gather` both responses, and then close the `async` contexts. Otherwise, as soon as you reach the `gather`, the two clients will be already close. Otherwise, you can open one `async` context at the time, `await` the response. Though, this will not exploit the `async` functionality – lsabi Apr 02 '22 at 09:58

0 Answers0