gpt4 book ai didi

python - 从 Airflow Postgres Hook 中检索完整连接 URI

转载 作者:行者123 更新时间:2023-12-04 04:12:09 25 4
gpt4 key购买 nike

有没有更简洁的方法从 Postgres 钩子(Hook)中获取完整的 URI? .get_uri()不包括“额外”参数,所以我像这样附加它们:

def pg_conn_id_to_uri(postgres_conn_id):
hook = PostgresHook(postgres_conn_id)
uri = hook.get_uri()

extra = hook.get_connection(postgres_conn_id).extra_dejson
params = [ f'{k}={v}' for k, v in extra.items() ]

if params:
params = '&'.join(params)
uri += f'?{params}'

return uri

最佳答案

如果清洁剂在这里并不一定意味着简洁,那么这里可能会起作用

from typing import Dict, Any

from psycopg2 import extensions

from airflow.hooks.postgres_hook import PostgresHook
from airflow.models.connection import Connection


def pg_conn_id_to_uri(postgres_conn_id: str) -> str:
# create hook & conn
hook: PostgresHook = PostgresHook(postgres_conn_id=postgres_conn_id)
conn: Connection = hook.get_connection(conn_id=postgres_conn_id)
# retrieve conn_args & extras
extras: Dict[str, Any] = conn.extra_dejson
conn_args: Dict[str, Any] = dict(
host=conn.host,
user=conn.login,
password=conn.password,
dbname=conn.schema,
port=conn.port)
conn_args_with_extras: Dict[str, Any] = {**conn_args, **extras}
# build and return string
conn_string: str = extensions.make_dsn(dsn=None, **conn_args_with_extras)
return conn_string

请注意,该片段未经测试

当然,我们仍然可以从这里剪掉更多的行(例如,通过使用 python 的语法糖 conn.__dict__.items() ),但我更喜欢清晰而不是简洁

提示来自 Airflow的 & pyscopg2的代码本身
  • PostgresHook
  • pyscopg2
  • 关于python - 从 Airflow Postgres Hook 中检索完整连接 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61528418/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com