Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python connect to postgresql with libpq-pgpass

I read there is a more secure way to connect to postgresql db without specifying password in source code using http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html. But unfortunatelly I was not able to find any examples of how to import it to my python program and how made my postgresql server to use this file. Please help.

like image 219
ovod Avatar asked Mar 02 '15 00:03

ovod


People also ask

How do I connect to a postgres database using Python?

How to Connect to PostgreSQL from Python? In order to connect to a PostgreSQL database instance from your Python script, you need to use a database connector library. In Python, you have several options that you can choose from. Some libraries that are written in pure Python include pg8000 and py-postgresql.

What is the module is used to connect to PostgreSQL in Python?

The psycopg module to connect a PostgreSQL The psycopg2 is the PostgreSQL connector commonly used by Python developers to connect to Python.

How do I connect to a postgres database?

In order to connect to a database you need to know the name of your target database, the host name and port number of the server, and what user name you want to connect as. psql can be told about those parameters via command line options, namely -d, -h, -p, and -U respectively.


1 Answers

You don't import it into your Python program. The point of .pgpass is that it is a regular file subject to the system's file permissions, and the libpq driver which libraries such as psycopg2 use to connect to Postgres will look to this file for the password instead of requiring the password to be in the source code or prompting for it.

Also, this is not a server-side file, but a client-side one. So, on a *nix box, you would have a ~/.pgpass file containing the credentials for the various connections you want to be able to make.

Edit in response to comment from OP:

Two main things need to happen in order for psycopg2 to correctly authenticate via .pgpass:

  1. Do not specify a password in the string passed to psycopg2.connect
  2. Make sure the correct entry is added to the .pgpass file for the user who will be connecting via psycopg2.

For example, to make this work for all databases for a particular user on localhost port 5432, you would add the following line to that user's .pgpass file:

localhost:5432:*:<username>:<password>

And then the connect call would be of this form:

conn = psycopg2.connect("host=localhost dbname=<dbname> user=<username>")

The underlying libpq driver that psycopg2 uses will then utilize the .pgpass file to get the password.

like image 94
khampson Avatar answered Oct 14 '22 10:10

khampson