如何使用python可调用中的postgres连接ID连接到postgres

时间:2021-04-23 16:22:17

标签: airflow

我正在使用 Airflow 的 python 运算符来调用 python 函数。 ERROR 出现在 try/except 块中。

def python_callable_new():
    print("Inside python callable ...")

    import psycopg2

    try:
        print("attempting database connection from python method.. ")
        conn = psycopg2.connect('postgres_defined_connection')
        print("success. ")
    except Exception as error:
        print("failed: ")
        print (error)
    return 'End of callable. '

    

with dag:
    start_task  = DummyOperator(  task_id= "start" )
    stop_task   = DummyOperator(  task_id= "stop"  )
    
    do_python_task = PythonOperator(
        task_id = 'do-py-operation',
        python_callable= python_callable_new,
    )

    extract_source_data = PostgresOperator(
        task_id='extract-cb-source-data',
        postgres_conn_id='postgres_defined_connection',
        sql='./sql_scripts/extract_csv_data.sql'
    )

    # csv_to_postgres

start_task >> do_python_task >> extract_source_data >> stop_task

基本上,我的问题是

  • 如何使用我的 'postgres_defined_connection' 连接到我的 Python 函数内的 postgres?
  • 当我使用 PostgresOperator 时它连接得很好,可以在 extract_source_data 任务中看到,但我需要在可调用函数中使用它。
  • 出现的错误是dsn无效:连接信息字符串中“postgres_defined_connection”之后缺少“=”

(仅供参考 - 我将 postgres_defined_connection 存储在使用 sqlalchemy 引擎和 PostgresHook 的单独的 connection.py 中)

1 个答案:

答案 0 :(得分:1)

psycopg2.connect 需要连接参数。如果将连接参数格式化为由空格分隔的键/值对,则可以将单个字符串传递给它们。这就是为什么它给你的错误消息缺少“=”。

有关详细信息,请参阅 psycopg documentation


要连接到 Airflow 中的 Postgres 数据库,您可以利用 PostgresHook,前提是您已创建连接。

from airflow.hooks.postgres_hook import PostgresHook
 
def execute_query_with_conn_obj(query):
    hook = PostgresHook(postgres_conn_id='my_connection')
    conn = hook.get_conn()
    cur = conn.cursor()
    cur.execute(query)

def execute_query_with_hook(query):
    hook = PostgresHook(postgres_conn_id='my_connection')
    hook.run(sql=query)

您也可以使用纯 Python 代码来实现。

def execute_query_with_psycopg(query):
    conn_args = dict(
        host='myhost';,
        user='admin',
        password='password',
        dbname='my_schema',
        port=5432)
    conn = psycopg2.connect(**conn_args)
    cur = conn.cursor()
    cur.execute(query)

def execute_query_with_psycopg_string(query):
    conn = psycopg2.connect("dbname=test user=postgres password=secret")
    cur = conn.cursor()
    cur.execute(query)