[Python] asyncpg when to use get a new connection with pool.acquire vs share one connection

Discussão em 'Python' iniciado por Stack, Abril 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm wondering when to share a asyncpg connection vs create a new one. Suppose I have:

    async def monitor(data_stream):
    # ...
    while True:
    # ...
    x, y = await data_stream.get_data()
    await conn.execute("INSERT INTO table (x, y) VALUES ($1, $2)", x, y)
    await asyncio.sleep(1)

    async def main():
    async with asyncpg.create_pool(user='user', password='pass', database='db', host='localhost') as pool:
    # ...
    await asyncio.gather(monitor(data_stream_1), monitor(data_stream_2), monitor(data_stream_3))

    asyncio.run(main())


    Should I place async with pool.acquire() as conn: in main (and share it across each method), at the top of monitor before the loop, or inside the body of the loop, and why? (assuming I pass pool as an argument if needed)

    From my understanding the connection pool keeps connections open and pool.acquire is very fast, so I should place it as low as possible, e.g. in the body of the loop.

    Continue reading...

Compartilhe esta Página