DevinM
DevinM

Reputation: 39

Psycopg2 Connection Class Attributes

The Psycopg2 connection class offers the str() magic method which returns some information about the connection such as the host, username, and database name.

How do you get that information from the connection class first hand? The documentation doesn't say how, and inspection.getsourcelines(conn.str) errors saying:

TypeError: "<connection object at 0xb690aecc; dsn: 'user=testuser password=xxxxxxxxx dbname=testdb', closed: 0>" is not a module, class, method, function, traceback, frame, or code object

I understand that Psycopg2 is a module that wraps the libpq library, but does that mean that some connection object attributes are left inaccessible?

Upvotes: 2

Views: 3138

Answers (3)

Matze
Matze

Reputation: 401

In a more up-to-date psycopg2 versions (my was 2.8.5) connection has a field called info. And info has these fields:

  • backend_pid
  • dbname
  • dsn_parameters
  • error_message
  • host
  • needs_password
  • options
  • parameter_status
  • password
  • port
  • protocol_version
  • server_version
  • socket
  • ssl_attribute
  • ssl_attribute_names
  • ssl_in_use
  • status
  • transaction_status
  • used_password
  • user

You can access theme like this:

connection.info.dbname

Upvotes: 4

DevinM
DevinM

Reputation: 39

After digging through some resources and picking the brains of some very nice guys in IRC, it seems as though there is no facility within psycopg2 to return the connection information in an object oriented way at this time. The output of conn.dns must be parsed in order to obtain the information. It can easily be done.

for i in connection.dsn.split(' '):
        if i.startswith('user'): username = i.split('=')[1]
        if i.startswith('host'): hostname = i.split('=')[1]
        if i.startswith('dbname'): dbname = i.split('=')[1]

The for loop is used due to the fact that the string returned by conn.dsn isn't always the same. It can sometimes include a hostname if a TCP connection is used, omit the host if a UNIX socket is used instead, or have additional information such as SSL or SSH tunnel information. In either case, this is a simple and quick way to parse the string.

Upvotes: 0

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125284

The dsn instance attribute:

conn = psycopg2.connect(database='cpn')
print conn.dsn    

Output:

dbname=cpn

Upvotes: 1

Related Questions