[英]Operators not referencing the same global variable
我正在定义一个全局变量timestamp
,其中多个运算符引用此变量。 似乎每个运算符运行时都重新定义了这个变量? 下面是一个最小的可重现示例。 我预计test
和test2
都会打印相同的时间戳,但它们在 Airflow 中打印不同的时间戳(相隔几秒)。
import datetime
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
start_date = datetime.datetime(
year=2022,
month=3,
day=30,
hour=18,
minute=0,
)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
def test():
print(timestamp)
def test2():
print(timestamp)
with DAG(
'airflow_test',
description='airflow test',
max_active_runs=1,
start_date=start_date,
) as dag:
test = PythonOperator(
task_id='test',
python_callable=test,
dag=dag
)
test2 = PythonOperator(
task_id='test2',
python_callable=test2,
dag=dag
)
test >> test2
当这个脚本由 Airflow 运行导致这种情况发生时,内部实际发生了什么?
我更喜欢使用气流默认内置,如:
from airflow.utils.dates import days_ago
例子:
project_cfg = {
'owner': 'airflow',
'email': ['your-email@example.com'],
'email_on_failure': True,
'start_date': days_ago(1),
'retries': 1,
'retry_delay': timedelta(hours=1),
}
对于您的问题,我更喜欢使用xcom来引用您的全局变量
另一种方法是制作一个函数并为每个任务调用它或制作局部变量
或试试这个:
with DAG(dag_id="test",
start_date=days_ago(3),
schedule_interval="@daily",
catchup=False) as dag:
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
@task
def test1():
return timestamp
@task
def test2():
return timestamp
test2(test1())
我希望它会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.