Reputation: 20304
How can I retrieve information about the host from the connection
object?
import psycopg2
connection = psycopg2.connect("host='localhost'")
In this case, I would want to know which port is being connected to. In another case I may simply want to parse out the host name for logging.
I could parse the connection.dsn
but there must be cleaner way since psycopg2
has already done the work of parsing this information (or has it?).
Upvotes: 1
Views: 871
Reputation: 15691
You can use the method get_dsn_parameters
(docs) to get a dictionary containing all the dsn parameters, including the port. Also available as .info.dsn_parameters
(docs).
For example:
port = connection.get_dsn_parameters()["port"]
or
port = connection.info.dsn_parameters["port"]
Whichever you like better.
Upvotes: 3