Airflow 如何在python可调用文件中使用postgres连接id连接到postgres

Airflow 如何在python可调用文件中使用postgres连接id连接到postgres,airflow,Airflow,我正在使用Airflow的python操作符调用python函数。错误发生在try/except块中 def python_callable_new(): print("Inside python callable ...") import psycopg2 try: print("attempting database connection from python method.. ") con

我正在使用Airflow的python操作符调用python函数。错误发生在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\u defined\u connection'在python函数中连接到postgres
  • 当我使用PostgresOperator时,它的连接很好,这可以在extract_source_data任务中看到,但我需要在可调用函数中使用它
  • 出现的错误是连接信息字符串中“postgres\u defined\u connection”之后缺少“=”的无效dsn

(仅供参考-我将postgres_定义的_连接存储在使用sqlalchemy引擎和Postgreshake的单独connections.py中)

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

有关更多信息,请参阅


若要连接到Airflow中的Postgres数据库,只要已创建连接,就可以利用

来自afflow.hooks.postgres\u hook导入postgres
def使用连接对象执行查询(查询):
hook=postgreshake(postgres\u conn\u id='my\u connection')
conn=hook.get_conn()
cur=连接光标()
当前执行(查询)
def使用_钩子执行_查询(查询):
hook=postgreshake(postgres\u conn\u id='my\u connection')
hook.run(sql=query)
您也可以使用纯Python代码来实现这一点

def使用psycopg执行查询(查询):
连接参数=dict(
host='myhost';,
user='admin',
password='password',
dbname='my_schema',
端口号=5432)
conn=psycopg2.connect(**conn_args)
cur=连接光标()
当前执行(查询)
def使用_psycopg_字符串执行_查询(查询):
conn=psycopg2.connect(“dbname=test user=postgres password=secret”)
cur=连接光标()
当前执行(查询)