Meer templates

Introductie tot Apache Airflow in Python

Mike Metzger

Data Engineer

Korte taakherinnering

  • Neem een lijst met bestandsnamen
  • Log/print "Reading <filename>"
  • Templateversie:
    templated_command="""
    echo "Reading {{ params.filename }}"
    """
    t1 = BashOperator(task_id='template_task',
         bash_command=templated_command,
         params={'filename': 'file1.txt'},
         dag=example_dag)
    
Introductie tot Apache Airflow in Python

Geavanceerdere 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
Introductie tot Apache Airflow in Python

Variabelen

  • Ingebouwde runtime-variabelen in Airflow
  • Bieden info over DAG-runs, taken en zelfs de systeemconfiguratie.
  • Voorbeelden:
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
Introductie tot Apache Airflow in Python

Macros

Naast andere is er ook een variabele {{ macros }}.

Dit is een verwijzing naar het Airflow-macropakket met handige objecten/methoden voor templates.

  • {{ macros.datetime }}: Het datetime.datetime-object
  • {{ macros.timedelta }}: Het timedelta-object
  • {{ macros.uuid }}: Python's uuid-object
  • {{ macros.ds_add('2020-04-15', 5) }}: Dagen bij een datum optellen; dit geeft 2020-04-20
Introductie tot Apache Airflow in Python

Laten we oefenen!

Introductie tot Apache Airflow in Python

Preparing Video For Download...