Ollie Glass
Ollie Glass

Reputation: 19993

Retrieve full connection URI from Airflow Postgres hook

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

Upvotes: 4

Views: 4769

Answers (1)

y2k-shubham
y2k-shubham

Reputation: 11627

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

Upvotes: 1

Related Questions