I am trying to write a pipeline where the postgres db should update with contents of a csv when it is brought to the folder. I have written a dag which creates the table and pushes the csv content when it is triggered from the web UI. Here's the code:
from datetime import datetime
from airflow import DAG
from airflow.utils.trigger_rule import TriggerRule
from airflow.operators.postgres_operator import PostgresOperator
from airflow.operators.python_operator import PythonOperator
import psycopg2
with DAG('Write_data_to_PG', description='This DAG is for writing data to postgres.',
schedule_interval='*/5 * * * *',
start_date=datetime(2018, 11, 1), catchup=False) as dag:
create_table = PostgresOperator(
task_id='create_table',
sql="""CREATE TABLE users(
id integer PRIMARY KEY,
email text,
name text,
address text
)
""",
)
def my_func():
print('Pushing data in database.')
conn = psycopg2.connect("host=localhost dbname=testdb user=testuser")
print(conn)
cur = conn.cursor()
print(cur)
with open('test.csv', 'r') as f:
next(f) # Skip the header row.
cur.copy_from(f, 'users', sep=',')
conn.commit()
print(conn)
print('DONE!!!!!!!!!!!.')
python_task = PythonOperator(task_id='python_task', python_callable=my_func)
create_table >> python_task
I am not able to figure out how to trigger the tasks when the csv is pasted/brought manually to the folder. Any help would be appreciated, thanks in advance.