Last active
September 1, 2022 21:13
-
-
Save agronholm/bf5bf041b3642dfdfed776b187a17868 to your computer and use it in GitHub Desktop.
Asyncpg reconnection problem demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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