簡體   English   中英

氣流ETL管道 - 在功能中使用計划日期?

[英]Airflow ETL pipeline - using schedule date in functions?

是否可以在Python函數中引用default_args start_date?

default_args = {
    'owner': 'airflow', 
    'depends_on_past': False, 
    'start_date': datetime(2016, 11, 21),
    'email': ['mmm.mm@mmm.com'], 
    'email_on_failure': True, 
    'email_on_retry': True,
    'retries': 1, 
    'retry_delay': timedelta(minutes=1)
}

我的python腳本主要使用subprocess來發出這個語句:

query = '"SELECT * FROM {}.dbo.{} WHERE row_date = \'{}\'"'.format(database,                                                             select_database(database)[table_int],
                                                                       query_date)
command = 'BCP {} queryout \"{}\" -t, -c -a 10240 -S "server" -T'.format(query, os.path.join(path, filename))

我想要運行的任務是使用BCP查詢'select * from table where date = {}'。 目前,我的python腳本具有日期變量的所有邏輯(默認為昨天)。 但是,最好引用default_arg並讓氣流處理日期。

因此,為了簡化,我想使用default_arg start_date和schedule(每天運行)來填充我的BCP命令中的變量。 這是正確的方法還是我應該在python腳本中保留日期邏輯?

這是正確的方法,但你真正需要的是execution_date ,而不是start_date 您可以使用provide_context=True參數通過provide_context=True的上下文將execution_date作為'ds'默認變量。 provide_context=True參數通過kwargs參數傳遞Jinja provide_context=True使用的一組默認變量。 您可以在文檔的相關部分中閱讀有關Default Variables和Jinja Templating的更多信息。 https://airflow.incubator.apache.org/code.html#default-variables https://airflow.incubator.apache.org/concepts.html#jinja-templating

您的代碼應如下所示:

def query_db(**kwargs):
    #get execution date in format YYYY-MM-DD
    query_date = kwargs.get('ds') 

    #rest of your logic

t_query_db = PythonOperator( task_id='query_db', python_callable=query_db, provide_context=True, dag=dag)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM