【问题标题】:How to specify a search path with SQL Alchemy and pg8000?如何使用 SQL Alchemy 和 pg8000 指定搜索路径?
【发布时间】:2023-02-18 17:46:25
【问题描述】:

我正在尝试使用 SQL Alchemy 和 pg8000 驱动程序连接到 postgres 数据库。我想为此连接指定一个搜索路径。使用 Psycopg 驱动程序,我可以通过做类似的事情来做到这一点

engine = create_engine(
    'postgresql+psycopg2://dbuser@dbhost:5432/dbname',
    connect_args={'options': '-csearch_path={}'.format(dbschema)})

但是,这不适用于 pg8000 驱动程序。有没有好的方法来做到这一点?

【问题讨论】:

    标签: python sqlalchemy pg8000


    【解决方案1】:

    您可以使用与psycopg2 几乎相同的方式使用pg8000,只需要将方案从postgresql+psycopg2 换成postgresql+pg8000

    完整的连接字符串定义在SQLAlchemy pg8000 docs

    postgresql+pg8000://user:password@host:port/dbname[?key=value&key=value...]
    

    但是虽然 psycopg2.connect 会将 kwargs 传递给服务器(如 options 及其内容),但 pg8000.connect 不会,因此没有设置 search_pathpg8000

    【讨论】:

    • 虽然这在没有搜索路径的情况下有效,但当我包含 connect_args={'options': '-csearch_path={}'.format(dbschema)} 时会出错,因为 pg8000 无法识别 options 键。
    【解决方案2】:

    SQLAlchemy docs 描述了如何做到这一点。例如:

    from sqlalchemy import create_engine, event, text
    
    
    engine = create_engine("postgresql+pg8000://postgres:postgres@localhost/postgres")
    
    @event.listens_for(engine, "connect", insert=True)
    def set_search_path(dbapi_connection, connection_record):
        existing_autocommit = dbapi_connection.autocommit
        dbapi_connection.autocommit = True
        cursor = dbapi_connection.cursor()
        cursor.execute("SET SESSION search_path='myschema'")
        cursor.close()
        dbapi_connection.autocommit = existing_autocommit
    
    
    with engine.connect() as connection:
        result = connection.execute(text("SHOW search_path"))
        for row in result:
            print(row)
    

    但是,正如文档中所说:

    SQLAlchemy 通常围绕保持这个概念组织 变量的默认值为 public

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 2011-02-21
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多