python - 为 psycopg2 : Getting race condition when setting search_path 中的所有连接查询设置架构

标签 python postgresql python-3.x schema psycopg2

我们的系统在 Ubuntu、python 3.4、postgres 9.4.x 和 psycopg2 上运行。

我们(将来会)使用模式在 devtestprod 环境之间进行拆分。我创建了一个方便的方法来创建与我们数据库的连接。它使用 json 连接配置文件来创建连接字符串。我想将连接配置为使用返回的连接对所有后续查询使用特定模式。我不希望我的查询具有硬编码架构,因为我们应该能够根据我们是处于开发、测试还是生产阶段/环境,轻松地在它们之间切换。

目前便捷的方法如下所示:

def connect(conn_config_file = 'Commons/config/conn_commons.json'):
    with open(conn_config_file) as config_file:    
        conn_config = json.load(config_file)

    conn = psycopg2.connect(
        "dbname='" + conn_config['dbname'] + "' " +
        "user='" + conn_config['user'] + "' " +
        "host='" + conn_config['host'] + "' " +
        "password='" + conn_config['password'] + "' " +
        "port=" + conn_config['port'] + " "
    )
    cur = conn.cursor()
    cur.execute("SET search_path TO " + conn_config['schema'])

    return conn

只要您给它时间执行设置的 search_path 查询,它就可以正常工作。不幸的是,如果我执行以下查询的速度太快,则会在未设置 search_path 的情况下发生竞争条件。我试图通过在 return conn 之前执行 conn.commit() 来强制执行,但是,这会将 search_path 重置为默认模式 postgres 这样它就不会使用,比如说,prod。在数据库或应用程序层的建议是更可取的,但是,我知道我们也可以在操作系统级别解决这个问题,也欢迎在这个方向上提出任何建议。

示例 json 配置文件如下所示:

{
    "dbname": "thedatabase",
    "user": "theuser",
    "host": "localhost",
    "password": "theusers_secret_password",
    "port": "6432",
    "schema": "prod"
}

非常感谢任何建议。

最佳答案

我认为更优雅的解决方案是在 connect()options 参数中设置 search_path,如下所示:

def connect(conn_config_file = 'Commons/config/conn_commons.json'):
    with open(conn_config_file) as config_file:    
        conn_config = json.load(config_file)

    schema = conn_config['schema']
    conn = psycopg2.connect(
        dbname=conn_config['dbname'],
        user=conn_config['user'],
        host=conn_config['host'],
        password=conn_config['password'],
        port=conn_config['port'],
        options=f'-c search_path={schema}',
    )
    return conn

当然,您可以使用“选项”作为连接字符串的一部分。但是使用关键字参数可以避免字符串连接的所有麻烦。

我在这个 psycopg2 feature request 中找到了这个解决方案.至于“options”参数本身,提到了here。 .

关于python - 为 psycopg2 : Getting race condition when setting search_path 中的所有连接查询设置架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32812463/

相关文章:

python - 将 GPU 与 python 包 bert_embeddings 和 mxnet 一起使用失败

postgresql - Postgresql 数据库中自定义数据类型的列的最大大小是多少?

python - 类型错误 : b'1' is not JSON serializable

python - 无法写入文件,PermissionError [Errno 13]

python - 芬尼克斯 : applying force on a particular point

python - 无法构建 matplotlib(png 包问题)

python - 绑定(bind)、发布、解除绑定(bind)、重复

postgresql - postgresQL, 函数

java - JPA Hibernate Postgres 错误 - 运算符不存在 : boolean = integer

python - 在 python 中提交后是否可以回滚 sqlite3 更改