[英]Apache airflow with conditional statements
我是 Airflow 的新手。 我想使用氣流操作符進行如下操作。
簡而言之,我想從數據庫表中讀取一些數據,並根據該表中列的值執行不同的任務。
這是我用來獲取數據的表。
+-----------+--------+
| task_name | status |
+-----------+--------+
| a | 1 |
| b | 2 |
| c | 4 |
| d | 3 |
| e | 4 |
+-----------+--------+
從上表中,我想選擇 status=4 的行,並根據它們的任務名稱運行相關的 jar 文件(為了運行 jar 文件,我打算使用 Bash Operator)。 我想使用 Airflow 執行此任務。 請注意,我使用的是 PostgreSQL。
這是我迄今為止實現的代碼。
from airflow.models import DAG
from airflow.operators.postgres_operator import PostgresOperator
from datetime import datetime, timedelta
from airflow import settings
#set the default attributes
default_args = {
'owner': 'Airflow',
'start_date': datetime(2020,10,4)
}
status_four_dag = DAG(
dag_id = 'status_check',
default_args = default_args,
schedule_interval = timedelta(seconds=5)
)
test=PostgresOperator(
task_id='check_status',
sql='''select * from table1 where status=4;''',
postgres_conn_id='test',
database='status',
dag=status_four_dag,
)
我被困在我想檢查 task_name 並調用相關 BashOperators 的地方。
感謝您的支持。 謝謝你。
XCom用於在任務之間傳遞消息。 將用於形成命令的 JAR 文件名和其他參數發送到xcom
並在后續任務中使用它。
例如,
check_status >> handle_status
check_status
- 從數據庫檢查狀態並將 JAR 文件名和參數寫入xcom
handle_status
- 從xcom
提取 JAR 文件名和參數,形成命令並執行它
示例代碼:
def check_status(**kwargs):
if randint(1, 100) % 2 == 0:
kwargs["ti"].xcom_push("jar_filename", "even.jar")
else:
kwargs["ti"].xcom_push("jar_filename", "odd.jar")
with DAG(dag_id='new_example', default_args=default_args) as dag:
t0 = PythonOperator(
task_id="check_status",
provide_context=True,
python_callable=check_status
)
t1 = BashOperator(
task_id="handle_status",
bash_command="""
jar_filename={{ ti.xcom_pull(task_ids='check_status', key='jar_filename') }}
echo "java -jar ${jar_filename}"
"""
)
t0 >> t1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.