Weitere Templates

Einführung in Apache Airflow mit Python

Mike Metzger

Data Engineer

Kurze Task-Erinnerung

  • Nimm eine Liste von Dateinamen
  • Gib „Reading <filename>“ ins Log/aus
  • Template-Version:
    templated_command="""
    echo "Reading {{ params.filename }}"
    """
    t1 = BashOperator(task_id='template_task',
         bash_command=templated_command,
         params={'filename': 'file1.txt'},
         dag=example_dag)
    
Einführung in Apache Airflow mit Python

Fortgeschrittenes Template

templated_command="""
{% for filename in params.filenames %}

echo "Reading {{ filename }}"
{% endfor %} """
t1 = BashOperator(task_id='template_task', bash_command=templated_command, params={'filenames': ['file1.txt', 'file2.txt']}, dag=example_dag)
Reading file1.txt
Reading file2.txt
Einführung in Apache Airflow mit Python

Variablen

  • Eingebaute Airflow-Laufzeitvariablen
  • Liefern Infos zu DAG-Runs, Tasks und sogar der Systemkonfiguration.
  • Beispiele:
Execution Date: {{ ds }}                              # YYYY-MM-DD
Execution Date, no dashes: {{ ds_nodash }}            # YYYYMMDD

Previous Execution date: {{ prev_ds }} # YYYY-MM-DD Prev Execution date, no dashes: {{ prev_ds_nodash }} # YYYYMMDD
DAG object: {{ dag }}
Airflow config object: {{ conf }}
1 https://airflow.apache.org/docs/stable/macros-ref.html
Einführung in Apache Airflow mit Python

Makros

Zusätzlich gibt es die Variable {{ macros }}.

Sie verweist auf das Airflow-Macros-Paket mit nützlichen Objekten/Methoden für Templates.

  • {{ macros.datetime }}: Das Objekt datetime.datetime
  • {{ macros.timedelta }}: Das Objekt timedelta
  • {{ macros.uuid }}: Pythons uuid-Objekt
  • {{ macros.ds_add('2020-04-15', 5) }}: Tage zu einem Datum addieren; hier: 2020-04-20
Einführung in Apache Airflow mit Python

Lass uns üben!

Einführung in Apache Airflow mit Python

Preparing Video For Download...