Retrieve full connection URI from Airflow Postgres hook

不打扰是莪最后的温柔 提交于 2020-05-16 22:03:17

问题


Is there a neater way to get the complete URI from a Postgres hook? .get_uri() doesn't include the "extra" params so I am appending them like this:

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

回答1:


If cleaner doesn't necessarily imply for brevity here, then here's something that might work

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

Note that the snippet is untested


Of course we can still trim off some more lines from here (for e.g. by using python's syntactic sugar conn.__dict__.items()), but I prefer clarity over brevity


The hints have been taken from Airflow's & pyscopg2's code itself

  • PostgresHook
  • pyscopg2


来源:https://stackoverflow.com/questions/61528418/retrieve-full-connection-uri-from-airflow-postgres-hook

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