<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kosen on Medium]]></title>
        <description><![CDATA[Stories by Kosen on Medium]]></description>
        <link>https://medium.com/@kosen_1?source=rss-8e91ef853b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ly-ANkor1PR6nkfQwf1MgA.jpeg</url>
            <title>Stories by Kosen on Medium</title>
            <link>https://medium.com/@kosen_1?source=rss-8e91ef853b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:28:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kosen_1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[HOW TO RUN A SIMPLE ETL PIPELINE USING PYTHON,AIRFLOW AND DOCKER.]]></title>
            <link>https://towardsdev.com/how-to-run-a-simple-etl-pipeline-using-python-airflow-and-docker-6e85db2954ff?source=rss-8e91ef853b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e85db2954ff</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Kosen]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 22:55:54 GMT</pubDate>
            <atom:updated>2024-08-14T14:56:59.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fp_GvWaeU5arRWf5FSHNQA.jpeg" /><figcaption>Image by Sagar Bhandge ,Medium</figcaption></figure><h4>Introduction</h4><p>ETLs,</p><p>A term mostly known by data engineers and often surrounded by a bit of technical wizardry. But what if I told you that this seemingly mysterious process is at the heart of the personalized content and product recommendations you see every day? In this article, I will break down how ETL pipelines work by using softwares like Python, Apache Airflow, and Docker to perform a simple ETL process from start to finish. This article assumes some basic programming knowledge, as delving into each line of code in detail could make the article quite lengthy. Let’s dive into the magic of ETL and see how it transforms raw data into something truly valuable.</p><p><strong>Project Steps</strong></p><p>1. Setting up Airflow and Docker</p><p>2. 1st Dag — Extracting data from a csv file</p><p>3. 2nd Dag — Creating a table to add our data to</p><p>4. 3rd Dag — Transforming the data</p><p>5. 4th Dag — Loading the data</p><p>6. Visualizing data in Pgadmin</p><p><strong>Setting up Airflow and Docker</strong></p><p>First things first, Apache Airflow is a tool for scheduling and managing data workflows, letting you automate and monitor tasks efficiently. Docker, on the other hand, packages applications and their dependencies into containers, ensuring consistency across different environments. Together, they simplify the setup and management of ETL processes.</p><p>To get started, create a new repository named ETL_Pipeline. Within this repository, set up three essential directories using the following command:</p><pre>mkdir -p ./dags ./logs ./plugins</pre><p>Next, create three key files: .env, Dockerfile, and docker-compose.yaml inside the ETL_Pipelines repository. In the docker-compose.yaml copy and paste the code below.</p><pre><br>---<br>version: &#39;3&#39;<br>x-airflow-common:<br>  &amp;airflow-common<br>  # In order to add custom dependencies or upgrade provider packages you can use your extended image.<br>  # Comment the image line, place your Dockerfile in the directory where you placed the docker-compose.yaml<br>  # and uncomment the &quot;build&quot; line below, Then run `docker-compose build` to build the images.<br>  image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.3.4}<br>  # build: .<br>  environment:<br>    &amp;airflow-common-env<br>    AIRFLOW__CORE__EXECUTOR: CeleryExecutor<br>    AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow<br>   <br>  <br>    # Other existing environment variables...<br>    AIRFLOW__LOGGING__BASE_LOG_FOLDER: /opt/airflow/logs<br>    AIRFLOW__LOGGING__REMOTE_LOGGING: &quot;False&quot;<br>    AIRFLOW__LOGGING__LOG_HANDLER: &quot;airflow.utils.log.file_task_handler.TimedRotatingFileHandler&quot;<br>    AIRFLOW__LOGGING__LOG_ROTATION_WHEN: &quot;M&quot;<br>    AIRFLOW__LOGGING__LOG_ROTATION_INTERVAL: &quot;10&quot;<br>    AIRFLOW__LOGGING__LOG_ROTATION_BACKUP_COUNT: &quot;1&quot;<br><br>     # For backward compatibility, with Airflow &lt;2.3<br>    AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow<br>    AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://airflow:airflow@postgres/airflow<br>    AIRFLOW__CELERY__BROKER_URL: redis://:@redis:6379/0<br>    AIRFLOW__CORE__FERNET_KEY: &#39;&#39;<br>    AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: &#39;true&#39;<br>    AIRFLOW__CORE__LOAD_EXAMPLES: &#39;true&#39;<br>    AIRFLOW__API__AUTH_BACKENDS: &quot;airflow.api.auth.backend.basic_auth,airflow.api.auth.backend.session&quot;<br><br>    _PIP_ADDITIONAL_REQUIREMENTS: ${_PIP_ADDITIONAL_REQUIREMENTS:-}<br>  volumes:<br>    - ./dags:/opt/airflow/dags<br>    - ./logs:/opt/airflow/logs<br>    - ./plugins:/opt/airflow/plugins<br>    - ./data:/usr/local/airflow/data<br>  user: &quot;${AIRFLOW_UID:-50000}:0&quot;<br>  depends_on:<br>    &amp;airflow-common-depends-on<br>    redis:<br>      condition: service_healthy<br>    postgres:<br>      condition: service_healthy<br><br>services:<br>  postgres:<br>    image: postgres:13<br>    environment:<br>      POSTGRES_USER: airflow<br>      POSTGRES_PASSWORD: airflow<br>      POSTGRES_DB: airflow<br>    volumes:<br>      - postgres-db-volume:/var/lib/postgresql/data<br>    ports:<br>      - 5432:5432<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;pg_isready&quot;, &quot;-U&quot;, &quot;airflow&quot;]<br>      interval: 5s<br>      retries: 5<br>    restart: always<br>  pgadmin:<br>      container_name: pgadmin4_container<br>      image: dpage/pgadmin4<br>      restart: always<br>      environment:<br>        PGADMIN_DEFAULT_EMAIL: admin@admin.com<br>        PGADMIN_DEFAULT_PASSWORD: root<br>        PGADMIN_LISTEN_PORT: 5050<br>      ports:<br>        - 5050:5050<br>      <br>  redis:<br>    image: redis:latest<br>    expose:<br>      - 6379<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;redis-cli&quot;, &quot;ping&quot;]<br>      interval: 5s<br>      timeout: 30s<br>      retries: 50<br>    restart: always<br><br>  airflow-webserver:<br>    &lt;&lt;: *airflow-common<br>    command: webserver<br>    ports:<br>      - 8080:8080<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:8080/health&quot;]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>  airflow-scheduler:<br>    &lt;&lt;: *airflow-common<br>    command: scheduler<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &#39;airflow jobs check --job-type SchedulerJob --hostname &quot;$${HOSTNAME}&quot;&#39;]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>  airflow-worker:<br>    &lt;&lt;: *airflow-common<br>    command: celery worker<br>    healthcheck:<br>      test:<br>        - &quot;CMD-SHELL&quot;<br>        - &#39;celery --app airflow.executors.celery_executor.app inspect ping -d &quot;celery@$${HOSTNAME}&quot;&#39;<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>    environment:<br>      &lt;&lt;: *airflow-common-env<br>      # Required to handle warm shutdown of the celery workers properly<br>      # See https://airflow.apache.org/docs/docker-stack/entrypoint.html#signal-propagation<br>      DUMB_INIT_SETSID: &quot;0&quot;<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>  airflow-triggerer:<br>    &lt;&lt;: *airflow-common<br>    command: triggerer<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &#39;airflow jobs check --job-type TriggererJob --hostname &quot;$${HOSTNAME}&quot;&#39;]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>  airflow-init:<br>    &lt;&lt;: *airflow-common<br>    entrypoint: /bin/bash<br>    # yamllint disable rule:line-length<br>    command:<br>      - -c<br>      - |<br>        function ver() {<br>          printf &quot;%04d%04d%04d%04d&quot; $${1//./ }<br>        }<br>        airflow_version=$$(AIRFLOW__LOGGING__LOGGING_LEVEL=INFO &amp;&amp; gosu airflow airflow version)<br>        airflow_version_comparable=$$(ver $${airflow_version})<br>        min_airflow_version=2.2.0<br>        min_airflow_version_comparable=$$(ver $${min_airflow_version})<br>        if (( airflow_version_comparable &lt; min_airflow_version_comparable )); then<br>          echo<br>          echo -e &quot;\033[1;31mERROR!!!: Too old Airflow version $${airflow_version}!\e[0m&quot;<br>          echo &quot;The minimum Airflow version supported: $${min_airflow_version}. Only use this or higher!&quot;<br>          echo<br>          exit 1<br>        fi<br>        if [[ -z &quot;${AIRFLOW_UID}&quot; ]]; then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: AIRFLOW_UID not set!\e[0m&quot;<br>          echo &quot;If you are on Linux, you SHOULD follow the instructions below to set &quot;<br>          echo &quot;AIRFLOW_UID environment variable, otherwise files will be owned by root.&quot;<br>          echo &quot;For other operating systems you can get rid of the warning with manually created .env file:&quot;<br>          echo &quot;    See: https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html#setting-the-right-airflow-user&quot;<br>          echo<br>        fi<br>        one_meg=1048576<br>        mem_available=$$(($$(getconf _PHYS_PAGES) * $$(getconf PAGE_SIZE) / one_meg))<br>        cpus_available=$$(grep -cE &#39;cpu[0-9]+&#39; /proc/stat)<br>        disk_available=$$(df / | tail -1 | awk &#39;{print $$4}&#39;)<br>        warning_resources=&quot;false&quot;<br>        if (( mem_available &lt; 4000 )) ; then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: Not enough memory available for Docker.\e[0m&quot;<br>          echo &quot;At least 4GB of memory required. You have $$(numfmt --to iec $$((mem_available * one_meg)))&quot;<br>          echo<br>          warning_resources=&quot;true&quot;<br>        fi<br>        if (( cpus_available &lt; 2 )); then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: Not enough CPUS available for Docker.\e[0m&quot;<br>          echo &quot;At least 2 CPUs recommended. You have $${cpus_available}&quot;<br>          echo<br>          warning_resources=&quot;true&quot;<br>        fi<br>        if (( disk_available &lt; one_meg * 10 )); then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: Not enough Disk space available for Docker.\e[0m&quot;<br>          echo &quot;At least 10 GBs recommended. You have $$(numfmt --to iec $$((disk_available * 1024 )))&quot;<br>          echo<br>          warning_resources=&quot;true&quot;<br>        fi<br>        if [[ $${warning_resources} == &quot;true&quot; ]]; then<br>          echo<br>          echo -e &quot;\033[1;33mWARNING!!!: You have not enough resources to run Airflow (see above)!\e[0m&quot;<br>          echo &quot;Please follow the instructions to increase amount of resources available:&quot;<br>          echo &quot;   https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html#before-you-begin&quot;<br>          echo<br>        fi<br>        mkdir -p /sources/logs /sources/dags /sources/plugins<br>        chown -R &quot;${AIRFLOW_UID}:0&quot; /sources/{logs,dags,plugins}<br>        exec /entrypoint airflow version<br>    # yamllint enable rule:line-length<br>    environment:<br>      &lt;&lt;: *airflow-common-env<br>      _AIRFLOW_DB_UPGRADE: &#39;true&#39;<br>      _AIRFLOW_WWW_USER_CREATE: &#39;true&#39;<br>      _AIRFLOW_WWW_USER_USERNAME: ${_AIRFLOW_WWW_USER_USERNAME:-airflow}<br>      _AIRFLOW_WWW_USER_PASSWORD: ${_AIRFLOW_WWW_USER_PASSWORD:-airflow}<br>      _PIP_ADDITIONAL_REQUIREMENTS: &#39;&#39;<br>    user: &quot;0:0&quot;<br>    volumes:<br>      - .:/sources<br><br>  airflow-cli:<br>    &lt;&lt;: *airflow-common<br>    profiles:<br>      - debug<br>    environment:<br>      &lt;&lt;: *airflow-common-env<br>      CONNECTION_CHECK_MAX_COUNT: &quot;0&quot;<br>    # Workaround for entrypoint issue. See: https://github.com/apache/airflow/issues/16252<br>    command:<br>      - bash<br>      - -c<br>      - airflow<br><br>  # You can enable flower by adding &quot;--profile flower&quot; option e.g. docker-compose --profile flower up<br>  # or by explicitly targeted on the command line e.g. docker-compose up flower.<br>  # See: https://docs.docker.com/compose/profiles/<br>  flower:<br>    &lt;&lt;: *airflow-common<br>    command: celery flower<br>    profiles:<br>      - flower<br>    ports:<br>      - 5555:5555<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:5555/&quot;]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>    restart: always<br>    depends_on:<br>      &lt;&lt;: *airflow-common-depends-on<br>      airflow-init:<br>        condition: service_completed_successfully<br><br>volumes:<br>  postgres-db-volume:</pre><p>In the .env file, add the following configuration:</p><pre>AIRFLOW_UID=50000</pre><p>For the Dockerfile:</p><pre>FROM apache/airflow:2.3.4<br><br># Install additional Python packages<br>RUN pip install --no-cache-dir pandas <br><br># Install additional system packages<br>USER root<br>RUN apt-get update &amp;&amp; apt-get install -y wget<br>USER airflow</pre><p>With everything in place, you can now start Airflow. Run the following commands:</p><pre>docker-compose up airflow-init<br>docker-compose up -d</pre><p>Airflow is now running successfully in docker. We can confirm this by checking the UI at localhost:8080 in our browser.</p><p><strong>Username</strong>: airflow</p><p><strong>Password</strong>: airflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNJSjHqvv0St-HZP8qR1cQ.jpeg" /><figcaption>Airflow User Interface</figcaption></figure><h4>Step 2: Extracting data from a csv file</h4><p>Since we have successfully launched airflow inside docker we can now begin our etl process. Every ETL process begins with extracting data we will use one of the simplest method which is extracting data from a locally situated csv file. Start by downloading and saving this <a href="https://github.com/Kos-en/ETL-Pipelines/tree/16ecaf2bcd26403a9bcd79d83428dadef83675ac/data/transformation_data">csv files</a> to a new folder named data inside your repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mu8a8I-G5lYEulIbH4iPGQ.jpeg" /></figure><p>Now we can finally create our first dag which will handle extraction of data from our csv file. Create a file named first_dag.py inside the dags folder. We will load a couple of packages to be used throughout the etl process.The code below shows how to create a dag for the extraction process.The code pulls data from the transformation_data file we previously created. The schedule_interval is set to &#39;daily&#39;, meaning the DAG is scheduled to run every day. This setting is particularly useful when dealing with data sources where the data is updated regularly, such as dynamic databases or APIs.</p><pre>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from airflow.providers.postgres.operators.postgres import PostgresOperator<br>from airflow.hooks.postgres_hook import PostgresHook<br>from datetime import datetime, timedelta<br>import pandas as pd<br>import logging<br><br># Configure logging<br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>    &#39;start_date&#39;: datetime(2024, 1, 1),<br>}<br><br>def extract_data(**context):<br>    crash_file_csv = &#39;/usr/local/airflow/data/transformation_data/traffic_crashes.csv&#39;<br>    vehicle_crash_csv = &#39;/usr/local/airflow/data/transformation_data/traffic_crash_vehicle.csv&#39;<br>    try:<br>        df_crashes = pd.read_csv(crash_file_csv)<br>        df_vehicles = pd.read_csv(vehicle_crash_csv)<br>        logger.info(&quot;CSV files read successfully&quot;)<br>        <br>        # Push the extracted data to XCom<br>        context[&#39;ti&#39;].xcom_push(key=&#39;df_crashes&#39;, value=df_crashes.to_json())<br>        context[&#39;ti&#39;].xcom_push(key=&#39;df_vehicles&#39;, value=df_vehicles.to_json())<br>        logger.info(&quot;Extracted data pushed to XCom&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;An error occurred while reading CSV files: {e}&quot;)<br><br>with DAG(<br>    dag_id=&#39;first_dag&#39;,<br>    default_args=default_args,<br>    schedule_interval=&#39;@daily&#39;,<br>    catchup=False<br>) as dag:<br>        #dag 1<br>    extract_task = PythonOperator(<br>        task_id=&#39;extract_data&#39;,<br>        python_callable=extract_data,<br>        provide_context=True,<br>    )</pre><h4><strong>Step 3: Creating a table</strong></h4><p>In this step, we’ll create a table where our transformed data will be loaded. However, before we proceed, we need to establish a connection to the database. To do this, open your web browser and navigate to localhost:8080, where the Airflow UI is hosted and add a connection with the details below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iE1wVu7nKX5yKqUwEB6uQg.jpeg" /></figure><p>After clicking save run the following code to create your second dag.</p><pre>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from airflow.providers.postgres.operators.postgres import PostgresOperator<br>from airflow.hooks.postgres_hook import PostgresHook<br>from datetime import datetime, timedelta<br>import pandas as pd<br>import logging<br><br># Configure logging<br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>    &#39;start_date&#39;: datetime(2024, 1, 1),<br>}<br><br>def extract_data(**context):<br>    crash_file_csv = &#39;/usr/local/airflow/data/transformation_data/traffic_crashes.csv&#39;<br>    vehicle_crash_csv = &#39;/usr/local/airflow/data/transformation_data/traffic_crash_vehicle.csv&#39;<br>    try:<br>        df_crashes = pd.read_csv(crash_file_csv)<br>        df_vehicles = pd.read_csv(vehicle_crash_csv)<br>        logger.info(&quot;CSV files read successfully&quot;)<br>        <br>        # Push the extracted data to XCom<br>        context[&#39;ti&#39;].xcom_push(key=&#39;df_crashes&#39;, value=df_crashes.to_json())<br>        context[&#39;ti&#39;].xcom_push(key=&#39;df_vehicles&#39;, value=df_vehicles.to_json())<br>        logger.info(&quot;Extracted data pushed to XCom&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;An error occurred while reading CSV files: {e}&quot;)<br>with DAG(<br>    dag_id=&#39;first_dag&#39;,<br>    default_args=default_args,<br>    schedule_interval=&#39;@daily&#39;,<br>    catchup=False<br>) as dag:<br>        #dag 1<br>    extract_task = PythonOperator(<br>        task_id=&#39;extract_data&#39;,<br>        python_callable=extract_data,<br>        provide_context=True,<br>    )<br>        #dag 2<br>    create_table = PostgresOperator(<br>        task_id = &#39;create_table&#39;,<br>        postgres_conn_id=&#39;postgres&#39;,<br>        sql=&#39;&#39;&#39;<br>            drop table if exists pipeline;<br>            create table pipeline(<br>                vehicle_types TEXT,<br>                crash_record_count INT<br>            );<br>        &#39;&#39;&#39;<br>    )<br>    # Set task dependencies<br>    extract_task &gt;&gt; create_table <br><br></pre><p>and now we have ourselves a table called pipeline with the columns vehicle_types and crash_record_count</p><p><strong>Step 4: Transforming the data</strong></p><p>Having created the data extracting dag we can now move to creating the transformation dag. Here we will use xcom to pull the data from the extraction process.Pandas is also used to transform the data inorder to provide an insight.</p><pre>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from airflow.providers.postgres.operators.postgres import PostgresOperator<br>from airflow.hooks.postgres_hook import PostgresHook<br>from datetime import datetime, timedelta<br>import pandas as pd<br>import logging<br><br># Configure logging<br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>    &#39;start_date&#39;: datetime(2024, 1, 1),<br>}<br><br>def extract_data(**context):<br>    crash_file_csv = &#39;/usr/local/airflow/data/transformation_data/traffic_crashes.csv&#39;<br>    vehicle_crash_csv = &#39;/usr/local/airflow/data/transformation_data/traffic_crash_vehicle.csv&#39;<br>    try:<br>        df_crashes = pd.read_csv(crash_file_csv)<br>        df_vehicles = pd.read_csv(vehicle_crash_csv)<br>        logger.info(&quot;CSV files read successfully&quot;)<br>        <br>        # Push the extracted data to XCom<br>        context[&#39;ti&#39;].xcom_push(key=&#39;df_crashes&#39;, value=df_crashes.to_json())<br>        context[&#39;ti&#39;].xcom_push(key=&#39;df_vehicles&#39;, value=df_vehicles.to_json())<br>        logger.info(&quot;Extracted data pushed to XCom&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;An error occurred while reading CSV files: {e}&quot;)<br><br>def transform_data(**context):<br>    try:<br>        # Pull the extracted data from XCom<br>        instance = context[&#39;ti&#39;]<br>        df_crashes_json = instance.xcom_pull(key=&#39;df_crashes&#39;, task_ids=&#39;extract_data&#39;)<br>        df_vehicles_json = instance.xcom_pull(key=&#39;df_vehicles&#39;, task_ids=&#39;extract_data&#39;)<br>        df_crashes = pd.read_json(df_crashes_json)<br>        df_vehicles = pd.read_json(df_vehicles_json)<br>        logger.info(&quot;Extracted data loaded successfully from XCom&quot;)<br><br>        # Clean data<br>        threshold_removed = df_crashes.dropna(axis=&#39;index&#39;, thresh=2, inplace=False)<br>        threshold_row = df_crashes[~df_crashes.index.isin(threshold_removed.index)]<br>        df_crashes.fillna(value={&#39;report_type&#39;: &#39;ON SCENE&#39;}, inplace=True)<br>        <br>        # Merge crashes and vehicles<br>        df = df_crashes.merge(df_vehicles, how=&#39;left&#39;, on=&#39;crash_record_id&#39;, suffixes=(&#39;_left&#39;, &#39;_right&#39;))<br>        df_agg = df.groupby(&#39;vehicle_type&#39;).agg({&#39;crash_record_id&#39;: &#39;count&#39;}).reset_index()<br>        <br>        # Transform column names for output data<br>        vehicle_mapping = {&#39;vehicle_type&#39;: &#39;vehicletypes&#39;}<br>        df_agg = df_agg.rename(columns=vehicle_mapping)<br>        <br>        # Push the transformed DataFrame to temporary file<br>        df_agg.to_csv(&#39;/tmp/agg_data.csv&#39;, index=None, header=False)<br>    except Exception as e:<br>        logger.error(f&quot;An error occurred during data transformation: {e}&quot;)<br><br>with DAG(<br>    dag_id=&#39;first_dag&#39;,<br>    default_args=default_args,<br>    schedule_interval=&#39;@daily&#39;,<br>    catchup=False<br>) as dag:<br><br>        #dag 1<br>    extract_task = PythonOperator(<br>        task_id=&#39;extract_data&#39;,<br>        python_callable=extract_data,<br>        provide_context=True,<br>    )<br>        #dag 2<br>    create_table = PostgresOperator(<br>        task_id = &#39;create_table&#39;,<br>        postgres_conn_id=&#39;postgres&#39;,<br>        sql=&#39;&#39;&#39;<br>            drop table if exists pipeline;<br>            create table pipeline(<br>                vehicletypes TEXT,<br>                crash_record_id INT<br>            );<br>        &#39;&#39;&#39;<br>    )  <br>       #dag 3<br>    transform_task = PythonOperator(<br>        task_id=&#39;transform_data&#39;,<br>        python_callable=transform_data,<br>        provide_context=True,<br>    )<br><br>    # Set task dependencies<br>    extract_task &gt;&gt; create_table &gt;&gt; transform_task<br><br><br></pre><p><strong>Step 5: Loading the data.</strong></p><p>Finally the final step of an ETL process which is loading the data to any desired target sytem this may be data warehouse, data lakes and in our case a relational database. Here we shall use PostgresHook to connect to our postgres database and copy our trasformed data from the temporary csv file to the table we previous created.</p><pre>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from airflow.providers.postgres.operators.postgres import PostgresOperator<br>from airflow.hooks.postgres_hook import PostgresHook<br>from datetime import datetime, timedelta<br>import pandas as pd<br>import logging<br><br># Configure logging<br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>    &#39;start_date&#39;: datetime(2024, 1, 1),<br>}<br><br>def extract_data(**context):<br>    crash_file_csv = &#39;/usr/local/airflow/data/transformation_data/traffic_crashes.csv&#39;<br>    vehicle_crash_csv = &#39;/usr/local/airflow/data/transformation_data/traffic_crash_vehicle.csv&#39;<br>    try:<br>        df_crashes = pd.read_csv(crash_file_csv)<br>        df_vehicles = pd.read_csv(vehicle_crash_csv)<br>        logger.info(&quot;CSV files read successfully&quot;)<br>        <br>        # Push the extracted data to XCom<br>        context[&#39;ti&#39;].xcom_push(key=&#39;df_crashes&#39;, value=df_crashes.to_json())<br>        context[&#39;ti&#39;].xcom_push(key=&#39;df_vehicles&#39;, value=df_vehicles.to_json())<br>        logger.info(&quot;Extracted data pushed to XCom&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;An error occurred while reading CSV files: {e}&quot;)<br><br>def transform_data(**context):<br>    try:<br>        # Pull the extracted data from XCom<br>        instance = context[&#39;ti&#39;]<br>        df_crashes_json = instance.xcom_pull(key=&#39;df_crashes&#39;, task_ids=&#39;extract_data&#39;)<br>        df_vehicles_json = instance.xcom_pull(key=&#39;df_vehicles&#39;, task_ids=&#39;extract_data&#39;)<br>        df_crashes = pd.read_json(df_crashes_json)<br>        df_vehicles = pd.read_json(df_vehicles_json)<br>        logger.info(&quot;Extracted data loaded successfully from XCom&quot;)<br><br>        # Clean data<br>        threshold_removed = df_crashes.dropna(axis=&#39;index&#39;, thresh=2, inplace=False)<br>        threshold_row = df_crashes[~df_crashes.index.isin(threshold_removed.index)]<br>        df_crashes.fillna(value={&#39;report_type&#39;: &#39;ON SCENE&#39;}, inplace=True)<br>        <br>        # Merge crashes and vehicles<br>        df = df_crashes.merge(df_vehicles, how=&#39;left&#39;, on=&#39;crash_record_id&#39;, suffixes=(&#39;_left&#39;, &#39;_right&#39;))<br>        df_agg = df.groupby(&#39;vehicle_type&#39;).agg({&#39;crash_record_id&#39;: &#39;count&#39;}).reset_index()<br>        <br>        # Transform column names for output data<br>        vehicle_mapping = {&#39;vehicle_type&#39;: &#39;vehicletypes&#39;}<br>        df_agg = df_agg.rename(columns=vehicle_mapping)<br>        <br>        # Push the transformed DataFrame to temporary file<br>        df_agg.to_csv(&#39;/tmp/agg_data.csv&#39;, index=None, header=False)<br>    except Exception as e:<br>        logger.error(f&quot;An error occurred during data transformation: {e}&quot;)<br><br>def load_data():<br>  try:<br>    # Connect to the Postgres connection<br>    hook = PostgresHook(postgres_conn_id = &#39;postgres&#39;)<br><br>    # Insert the data from the the temporary CSV file into the postgres database<br>    hook.copy_expert(<br>        sql = &quot;COPY pipeline FROM stdin WITH DELIMITER as &#39;,&#39;&quot;,<br>        filename=&#39;/tmp/agg_data.csv&#39;<br>    )<br>    logger.info(&quot;Data loaded successfully&quot;)<br>  except Exception as e:<br>      logger.error(f&#39;An error occured during data loading{e}&#39;)<br><br>with DAG(<br>    dag_id=&#39;first_dag&#39;,<br>    default_args=default_args,<br>    schedule_interval=&#39;@daily&#39;,<br>    catchup=False<br>) as dag:<br>        #dag 1<br>    extract_task = PythonOperator(<br>        task_id=&#39;extract_data&#39;,<br>        python_callable=extract_data,<br>        provide_context=True,<br>    )<br>        #dag 2<br>    create_table = PostgresOperator(<br>        task_id = &#39;create_table&#39;,<br>        postgres_conn_id=&#39;postgres&#39;,<br>        sql=&#39;&#39;&#39;<br>            drop table if exists pipeline;<br>            create table pipeline(<br>                vehicletypes TEXT,<br>                crash_record_id INT<br>            );<br>        &#39;&#39;&#39;<br>    )<br>       #dag 3<br>    transform_task = PythonOperator(<br>        task_id=&#39;transform_data&#39;,<br>        python_callable=transform_data,<br>        provide_context=True,<br>    )<br>        #dag 4<br>    load_task = PythonOperator(<br>        task_id=&#39;load_data&#39;,<br>        python_callable=load_data,<br>        provide_context=True,<br>    )<br><br>    # Set task dependencies<br>    extract_task &gt;&gt; create_table &gt;&gt; transform_task &gt;&gt; load_task<br><br></pre><p>We shall now run the full pipeline in Localhost:8080to see if the ETL process was successful. You should be able to view all the DAGs present ,scroll down and look for first_dag and activate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vR1e9oh4mISL-gQJQX8yTA.jpeg" /></figure><p>After activating the dag you should see it pop up in the Active DAGs section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFpvdY05qsucZ2BFyMA91g.jpeg" /></figure><p>At this point, you should see that first_dag is active. Next, scroll to the &quot;Links&quot; section as shown above and click on &quot;Graph&quot; to visualize the workflow and check if it has been executed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEO36-g3mGyqTMwTFrU1IA.jpeg" /></figure><p>Since all are green this means all the DAGs have been successful and the whole ETL process has succeeded. Great! you have now created a simple etl pipeline using python, docker and airflow. The final step will be to view this data in pgadmin.</p><p>NB: In each of the ETL steps u can view if the process has been successful in the same manner as shown above.</p><p><strong>Step 6: Viewing the data in pgadmin</strong></p><p>To launch pgAdmin,go to localhost:5050. The UI should already be running because of the image specified in the docker-compose.yaml file. To log in, enter the Username and Password from the docker-compose file which in my case is</p><p><strong>Username</strong>: <a href="/service/mailto:admin@admin.com">admin@admin.com</a></p><p><strong>Password</strong>: root</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6yFLzGLMmRAY9HPxdMqCQ.jpeg" /></figure><p>After inputing the password you will create a new server where u will input the following details.</p><p>Here you can put any name you want to give to your server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrjC5xRDTs6iSD5kMj1v_A.jpeg" /></figure><p>Here the username and password have to be what you configured in the docker-compose.yaml. I used:</p><p><strong>Username</strong>:airflow</p><p><strong>Password</strong>:airflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0jwRPofKGiLIsSx8RUMug.jpeg" /></figure><p>The crucial part here is the hostname or address. In this context, you need the address of your PostgreSQL container running within Docker. To find this address, you can use the following commands:</p><pre>(base) joe@Seeking-the-invisible:~/Desktop/Etl Pipelines(main⚡) » docker ps<br>(base) joe@Seeking-the-invisible:~/Desktop/Etl Pipelines(main⚡) » docker inspect -f &#39;{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}&#39; 3f349eed3617</pre><p>The id 3f349eed3617 should be specific to your container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOWP6R-wQHdAXPOrnVg74g.jpeg" /></figure><p>After getting the address copy and paste it in the pgadmin hostname/address section and click save.</p><p>The last-step is to head over to the pipeline table which should be in the airflow database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ys2s9kYNYf0AwAj_5YsZw.jpeg" /></figure><p>Great we now have an ETL pipeline that gives out a table of the number of each vehicle type involved in a crash . Thanks for reading.</p><p><strong>Github</strong>:<a href="https://github.com/Kos-en/ETL-Pipelines">https://github.com/Kos-en/ETL-Pipelines</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e85db2954ff" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-to-run-a-simple-etl-pipeline-using-python-airflow-and-docker-6e85db2954ff">HOW TO RUN A SIMPLE ETL PIPELINE USING PYTHON,AIRFLOW AND DOCKER.</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>