【问题标题】:Reading PSYCOPG2 connection credential from a file in python从 python 文件中读取 PSYCOPG2 连接凭据
【发布时间】:2018-09-11 11:00:26
【问题描述】:

我已将红移连接凭据存储在本地系统的文件 test.txt 中。文件内容为:

host='abcxyz.redshift.amazonaws.com',
user='def',
port=5439,
password='123456',
dbname='ijk'

我在我的python代码中调用文件的内容如下:

import psycopg2
with open ('filepath\test.txt', 'r') as myfile:
    data = myfile.read()
conn = psycopg2.connect(data)
cur = conn.cursor()

但是,它给出了以下错误:

psycopg2.ProgrammingError: 无效 dsn: 在连接中的“数据”之后缺少“=” 信息字符串

谁能告诉我我到底哪里出错了?

我尝试将文件内容放在引号内,但这也不起作用。

【问题讨论】:

  • 这与凭据在文件中的存储方式有关吗?是否需要以不同的方式格式化?

标签: python-2.7 amazon-redshift psycopg2


【解决方案1】:

我可以通过创建如下文件来做到这一点:

abcxyz.redshift.amazonaws.com
def
5439
123456
ijk

然后将其保存为 test.txt 然后创建一个空列表并将文件中的每一行附加到列表中。然后使用 psycopg2 作为:

conn = psycopg2.connect(host = cred_detail[0][0],
                        user = cred_detail[1][0],
                        port = cred_detail[2][0],
                        password = cred_detail[3][0],
                        dbname = cred_detail[4][0])
cur = conn.cursor()

这不是存储和读取凭据的好方法,但到目前为止,这解决了我的目的。请建议任何在通过 Python 连接到 AWS Redshift 时隐藏/隐藏凭证的好方法。

【讨论】:

    【解决方案2】:

    您的配置文件应包含以下内容,并且可以正常工作。请试试。 我同意你的观点,你的解决方案不好,因此在这里回答,以便对其他人有用。

    host=yourhost.redshift.amazonaws.com
    user=redshift-user
    port=5439
    password=redshift-password
    dbname=redshift-database
    

    关于你在自我回答中的问题,

    在通过 Python 连接到 AWS Redshift 时,请提出任何隐藏/隐藏凭证的好方法。

    保护配置文件的方法有很多种,每种方法都各有利弊。我建议我使用一种简单的方法(在 Unix/Linux 环境中),将您的属性文件置于特定用户下,并且只保留对用户的读/写访问权限。

    【讨论】:

      【解决方案3】:

      您可以遵循 postgresql 的本地 ~/.pgpass 支持。有关详细信息,请参阅https://www.postgresql.org/docs/9.1/libpq-pgpass.html

      示例 ~/.pgpass 文件:

      ## hostname:port:database:username:password
      ## non-admin user
      db.example.com:5432:db1:foo:apple
      ## admin user
      db.example.com:5432:db1:postgres:pear
      

      我通过 jupyter 实验室设置了数据库,并使用 psycopg2 作为 postgres 驱动程序。我使用以下字符串,postgres 为用户选择适当的凭据: foo 和数据库 db1 从 ~/.pgpass 文件。我没有尝试过psycopg2.connect 命令,但它应该适用于 ~/.pgpass 文件。

      postgresql://foo@db.example.com/db1
      

      如果需要 SSL,则使用以下内容:

      postgresql://foo@db.example.com/db1?sslmode=require
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-14
        • 2011-04-16
        • 2019-07-09
        • 1970-01-01
        • 2022-09-27
        • 2020-12-18
        • 1970-01-01
        相关资源
        最近更新 更多