Skip to content

Call async request several times with the same AsyncClient with asyncio.run() is causing RuntimeError: Event loop is closed #2473

Closed

Description

@PFaurel

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':

client = httpx.AsyncClient()

async def home():
    r = await client.get('https://www.example.com/')
    return r

asyncio.run(home())
asyncio.run(home())  # => RuntimeError: Event loop is closed
asyncio.run(home())  # => RuntimeError: Event loop is closed
asyncio.run(home())  # => RuntimeError: Event loop is closed

Activity

  1. changed the title [-]Call async request sevreal times with the same AsyncClient with asyncio.run() is causing RuntimeError: Event loop is closed[/-] [+]Call async request several times with the same AsyncClient with asyncio.run() is causing RuntimeError: Event loop is closed[/+] on Dec 1, 2022
  2. lovelydinosaur commented on Dec 2, 2022

    @lovelydinosaur
    Member

    So, yeah...

    Don't try to share an AsyncClient across multiple event loops. That won't work, and I'd assume we probably wouldn't be able to make it work.

    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())
  3. locked and limited conversation to collaborators on Dec 2, 2022
  4. converted this issue into a discussion #2489 on Dec 2, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions