Angel
Angel

Reputation: 2865

How list all opened connections in sqlalchemy?

Recently I had an error sqlalchemy in my production server.

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "myserver.com" (myip), port myport failed: FATAL: remaining connection slots are reserved for non-replication superuser connections

However this application only has a few users (1 or 2) and it's not possible that the database server is not powerful enough.

My application is 100% tested and I would also like to test the number of opened connections.

Is there a way to list opened connection in sqlalchemy?

Upvotes: 2

Views: 3216

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55670

The default connection pool has methods which report connection states:

  • Pool.status(): report pool state including open connections
  • Pool.checkedout(): number of open connections
  • Pool.checkedin(): number of closed connections in the pool
>>> engine = sa.create_engine('postgresql:///test')
>>> engine.pool.status()
'Pool size: 5  Connections in pool: 0 Current Overflow: -5 Current Checked out connections: 0'
>>> conn1 = engine.connect()
>>> conn2 = engine.connect()
>>> engine.pool.status()
'Pool size: 5  Connections in pool: 0 Current Overflow: -3 Current Checked out connections: 2'
>>> engine.pool.checkedin()
0
>>> engine.pool.checkedout()
2
>>> conn1.close()
>>> engine.pool.checkedin()
1
>>> engine.pool.checkedout()
1
>>> conn2.close()
>>> engine.pool.status()
'Pool size: 5  Connections in pool: 2 Current Overflow: -3 Current Checked out connections: 0'

Upvotes: 6

Related Questions