Search code examples
pythonpostgresqlpsycopg2

How to handle ever-changing password in psycopg2?


Similar to how to handle ever-changing password in sqlalchemy+psycopg2? I an faced with a PostgreSQL setup where passwords are rotated frequently. My application runs longer than a password is valid and I need to use the new password for any new connections being made by the application.

I am using a psycopg2.pool.ThreadedConnectionPool.

How can I update the pool to use the new password for any new connection it makes after I acquired a new password?

I can not and do not need to kill existing connections, they keep working as long as they are alive. I just need to make sure that new connections use the new password.


Solution

  • You can create your own subclass of ThreadedConnectionPool and re-implement _connect() to get the credentials before connecting.

    Alternatively you can change the pool's ._args and ._kwargs attributes, even though they are private by convention. They are passed to connect() to create new connections.