Skip to content

Instantly share code, notes, and snippets.

@agronholm
Last active September 1, 2022 21:13
Show Gist options
  • Save agronholm/bf5bf041b3642dfdfed776b187a17868 to your computer and use it in GitHub Desktop.
Save agronholm/bf5bf041b3642dfdfed776b187a17868 to your computer and use it in GitHub Desktop.
Asyncpg reconnection problem demo
from asyncio import run, sleep
from asyncpg import InterfaceError
from sqlalchemy.ext.asyncio import create_async_engine
async def main():
engine = create_async_engine("postgresql+asyncpg://postgres:secret@localhost/testdb")
while True:
while True:
conn = await engine.raw_connection()
raw_conn = conn.driver_connection
try:
await raw_conn.execute("SELECT 1")
print("Connection established")
except Exception as exc:
conn.close()
print("Error establishing connection:", exc)
await sleep(1)
else:
break
while True:
try:
await raw_conn.execute("SELECT 1")
print("Connection still works")
await sleep(1)
except InterfaceError as exc:
conn.close()
print("Error in loop:", exc)
break
except BaseException:
conn.close()
raise
run(main())
services:
postgresql:
image: postgres
ports:
- 127.0.0.1:5432:5432
environment:
POSTGRES_DB: testdb
POSTGRES_PASSWORD: secret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment