python connect to postgresql with libpq-pgpass

馋奶兔 提交于 2019-12-09 17:17:33

问题


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.


回答1:


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.




回答2:


#!/usr/bin/python
import psycopg2
import sys
import pprint

def main():
    conn_string = "host='127.0.0.1' dbname='yourdatabsename'  user='yourusername' password='yourpassword'"
print "Connecting to database\n ->%s" % (conn_string)
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute("SELECT * FROM tablename")


records = cursor.fetchall()
pprint.pprint(records)

if __name__ == "__main__":
    main()


来源:https://stackoverflow.com/questions/28800880/python-connect-to-postgresql-with-libpq-pgpass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!