Call async request several times with the same AsyncClient with asyncio.run() is causing RuntimeError: Event loop is closed #2489
Answered
by
lovelydinosaur
PFaurel
asked this question in
Potential Issue
-
|
When AsyncClient is used several times with an async function that's sending an http request, the first time is successful, all other attempts are failing with RuntimeError exception and "Event loop is closed" error message. To reproduce: import httpx if name == 'main': |
Beta Was this translation helpful? Give feedback.
Answered by
lovelydinosaur
Dec 2, 2022
Replies: 1 comment 1 reply
-
|
So, yeah... Don't try to share an You either want... async def home():
async with httpx.AsyncClient() as client:
r = await client.get('https://www.example.com/')
return r
# Not sure why you'd want to do this, but at least it's not broken now...
asyncio.run(home())
asyncio.run(home())
asyncio.run(home())
asyncio.run(home())Or more sensibly... async def home(client):
r = await client.get('https://www.example.com/')
return r
async def main():
# Structured correctly.
# Single client shared across multiple requests.
async with httpx.Client() as client:
await home(client)
await home(client)
await home(client)
await home(client)
asyncio.run(main()) |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
lovelydinosaur
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So, yeah...
Don't try to share an
AsyncClientacross multiple event loops. That won't work, and I'd assume we probably wouldn't be able to make it work.You either want...
Or more sensibly...