Airflow operators

Introduction to Apache Airflow in Python

Mike Metzger

Data Engineer

Operators

  • Represent a single task in a workflow
  • Run independently (usually)
  • Generally do not share information
  • Various operators to perform different tasks
@dag(
  dag_id="Example_Dag"
)
def example_dag():
  @task
  def task1():
    return "The result from task1"

  task1()

example_dag()
Introduction to Apache Airflow in Python

@task (PythonOperator)

  • Executes a Python function
  • Any Python function can be decorated with @task
  • Can pass data with other functions / tasks
from airflow.sdk import task

@task def printme(): print("This goes in the logs!")
printme()
Introduction to Apache Airflow in Python

@task arguments

  • Can pass arguments to task / function like an ordinary Python function
@task
def printme(name: str):
    print(f"Hi {name} - This goes in the logs!")

printme(name='DataCamp')
# Adds: # Hi DataCamp - This goes in the logs! # to the Airflow logs
Introduction to Apache Airflow in Python

@task.bash (BashOperator)

@task.bash
def bash_example():
  return "echo 'Example!'"

bash_example()
@task.bash
def run_cleanup():
  return "runcleanup.sh"

run_cleanup()
  • Executes a given Bash command or script
  • Runs the command in a temporary directory
  • Can specify environment variables for the command
Introduction to Apache Airflow in Python

Task dependencies

  • Each Dag has a set of tasks to complete
  • Task dependencies specify running order
  • Different methods to specify dependencies

 

Airflow Dag of connected tasks showing dependency order between them

Introduction to Apache Airflow in Python

Bitshift syntax

>> and <<

task1() >> task2()

# task1 completes before task2 starts
task1() >> task2() >> task3()
# task1 completes before task2 and task2 completes before task3
task1() >> task3() task2() >> task3()
# task1 and task2 can run together but both must complete before task3 runs
Introduction to Apache Airflow in Python

Bitshift syntax example

# Download sales data before reconciling
download_sales_data() >> reconcile()

# Download inventory data before reconciling
download_inventory_data() >> reconcile()

 

  • Both must complete before reconciling, but order isn't specified
Introduction to Apache Airflow in Python

Let's practice!

Introduction to Apache Airflow in Python

Preparing Video For Download...