在 AWS MWAA 中,要在 DAG 中调用 Python 代码,需要将 Python 代码保存在 S3 存储桶中。在 DAG 中,可以通过 S3 来引用 Python 代码。
例如,假设我们在 S3 存储桶“my_bucket”中有一个名为“my_script.py”的脚本,我们可以在 DAG 文件中使用以下代码来引用该脚本:
from airflow.operators.bash_operator import BashOperator
from airflow.utils.dates import days_ago
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': days_ago(1),
'email': ['airflow@example.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5),
}
with DAG(
'my_dag',
default_args=default_args,
description='A simple tutorial DAG',
schedule_interval=timedelta(days=1),
) as dag:
t1 = BashOperator(
task_id='print_date',
bash_command='date',
)
t2 = BashOperator(
task_id='run_script',
bash_command='python3 /usr/local/airflow/dags/my_script.py',
)
t1 >> t2
在 DAG 中,我们可以使用 BashOperator 来运行 Python 脚本。在上面的代码示例中,我们已添加了一个“run_script”任务,并为其提供了一个名为“my_script.py”的 Python 脚本路径。请注意,路径是相对路径,取决于您在容器中使用的位置。在本示例中,Python 脚本位于“/usr/local/airflow/dags/my_script.py”路径中。
因此,将 Python 代码保存在 S3 存储桶中,并在 DAG 中使用 BashOperator 来调用该脚本,是在 AWS MWAA 中使用 Python 代码的最佳实