[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n\n.idea*\n*.pid\n*.db\n*.cfg\nlogs/"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2019 Varya\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "This is a small example of the workflow built with Apache Airflow.\n\nYou can find slides [here](https://www.slideshare.net/varyakarpenko5/airflow-for-beginners) and watch the talk [here](https://www.youtube.com/watch?v=YWtfU0MQZ_4)\n\nThe goal is to set up a data pipline to get a fresh portion of Stack Overflow questions with tag `pandas` to our mailbox daily.\n\nA small python script could do the job, but for the learning purposes we choose to overengineer it.\n\nBy writing this workflow we will learn the main concepts of Apache Airflow, such as:\n    \n* Operators\n* DAG\n* Tasks\n* Hooks\n* Variables\n* Connections\n* XComs\n\nHappy learning 🤓\n\n### Helpful resources\n\n📝 [Apache Airflow Documentation](https://airflow.apache.org/)\n\n#### Apache Airflow tutorials for beginners\n\n📝 [Apache Airflow Tutorial for Data Pipelines](https://blog.godatadriven.com/practical-airflow-tutorial)\n\n📝 [Apache Airflow for the confused](https://medium.com/nyc-planning-digital/apache-airflow-for-the-confused-b588935669df)\n\n📝 [Airflow: Tutorial and Beginners Guide](https://www.polidea.com/blog/apache-airflow-tutorial-and-beginners-guide/)\n\n📝 [ETL Pipelines With Airflow](http://michael-harmon.com/blog/AirflowETL.html)\n\n\n#### Some more\n\n📰 [ETL best principles](https://gtoonstra.github.io/etl-with-airflow/principles.html)\n\n📰 [Managing Dependencies in Apache Airflow](https://www.astronomer.io/guides/managing-dependencies/)\n\n📝 [Getting Started with Airflow Using Docker](http://www.marknagelberg.com/getting-started-with-airflow-using-docker/)\n\n🎧 [Putting Airflow Into Production](https://overcast.fm/+H1YNx1QJE)\n\n📝 [How to configure SMTP server for apache airflow](https://stackoverflow.com/questions/51829200/how-to-set-up-airflow-send-email)\n\n\nIf you have any questions or would like to get in touch with me, please drop me a message to `hello@varya.io`\n"
  },
  {
    "path": "dags/dags.py",
    "content": "from datetime import datetime, timedelta\n\nfrom airflow import DAG\nfrom airflow.operators.email_operator import EmailOperator\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom airflow.operators.python_operator import PythonOperator\n\nfrom utils import insert_question, write_questions_to_s3, render_template\n\nfrom dags.utils import insert_question_to_db\n\ndefault_args = {\n    \"owner\": \"me\",\n    \"depends_on_past\": False,\n    \"start_date\": datetime(2019, 10, 9),\n    \"email\": [\"my_email@mail.com\"],\n    \"email_on_failure\": False,\n    \"email_on_retry\": False,\n    \"retries\": 0,\n    \"retry_delay\": timedelta(minutes=1),\n    \"schedule_interval\": \"@daily\",\n}\n\nwith DAG(\"stack_overflow_questions\", default_args=default_args) as dag:\n\n    Task_I = PostgresOperator(\n        task_id=\"create_table\",\n        postgres_conn_id=\"postgres_connection\",\n        database=\"stack_overflow\",\n        sql=\"\"\"\n        DROP TABLE IF EXISTS public.questions;\n        CREATE TABLE public.questions\n        (\n            title text,\n            is_answered boolean,\n            link character varying,\n            score integer,\n            tags text[],\n            question_id integer NOT NULL,\n            owner_reputation integer\n        )\n        \"\"\",\n    )\n\n    Task_II = PythonOperator(\n        task_id=\"insert_question_to_db\", python_callable=insert_question_to_db\n    )\n\n    Task_III = PythonOperator(\n        task_id=\"write_questions_to_s3\", python_callable=write_questions_to_s3\n    )\n\n    Task_IV = PythonOperator(\n        task_id=\"render_template\",\n        python_callable=render_template,\n        provide_context=True,\n    )\n\n    Task_V = EmailOperator(\n        task_id=\"send_email\",\n        provide_context=True,\n        to=\"my_email@mail.com\",\n        subject=\"Top questions with tag 'pandas' on {{ ds }}\",\n        html_content=\"{{ task_instance.xcom_pull(task_ids='render_template', key='html_content') }}\",\n    )\n\nTask_I >> Task_II >> Task_III >> Task_IV >> Task_V\n\n"
  },
  {
    "path": "dags/email_template.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Title</title>\n</head>\n<body>\n<ul>\n{% for question in questions %}\n   <li>\n       <a href=\"{{question['link']}}\">{{question['title'].capitalize()}}</a> tagged: <strong>{{', '.join(question['tags'])}}</strong>\n   </li>\n{% endfor %}\n</ul>\n</body>\n</html>"
  },
  {
    "path": "dags/utils.py",
    "content": "import json\nimport os\nfrom datetime import datetime, timedelta\n\nimport requests\nfrom airflow.hooks.S3_hook import S3Hook\nfrom airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import Variable\n\nfrom jinja2 import Environment, FileSystemLoader\n\nS3_FILE_NAME = f\"{datetime.today().date()}_top_questions.json\"\n\n\ndef call_stack_overflow_api() -> dict:\n    \"\"\" Get first 100 questions created two days ago sorted by user votes \"\"\"\n\n    stack_overflow_question_url = Variable.get(\"STACK_OVERFLOW_QUESTION_URL\")\n\n    today = datetime.now()\n    three_days_ago = today - timedelta(days=7)\n    two_days_ago = today - timedelta(days=5)\n\n    payload = {\n        \"fromdate\": int(datetime.timestamp(three_days_ago)),\n        \"todate\": int(datetime.timestamp(two_days_ago)),\n        \"sort\": \"votes\",\n        \"site\": \"stackoverflow\",\n        \"order\": \"desc\",\n        \"tagged\": Variable.get(\"TAG\"),\n        \"client_id\": Variable.get(\"STACK_OVERFLOW_CLIENT_ID\"),\n        \"client_secret\": Variable.get(\"STACK_OVERFLOW_CLIENT_SECRET\"),\n        \"key\": Variable.get(\"STACK_OVERFLOW_KEY\"),\n    }\n\n    response = requests.get(stack_overflow_question_url, params=payload)\n\n    for question in response.json().get(\"items\", []):\n        yield {\n            \"question_id\": question[\"question_id\"],\n            \"title\": question[\"title\"],\n            \"is_answered\": question[\"is_answered\"],\n            \"link\": question[\"link\"],\n            \"owner_reputation\": question[\"owner\"].get(\"reputation\", 0),\n            \"score\": question[\"score\"],\n            \"tags\": question[\"tags\"],\n        }\n\n\ndef insert_question_to_db():\n    \"\"\" Inserts a new question to the database \"\"\"\n\n    insert_question_query = \"\"\"\n        INSERT INTO public.questions (\n            question_id,\n            title,\n            is_answered,\n            link,\n            owner_reputation, \n            score, \n            tags)\n        VALUES (%s, %s, %s, %s, %s, %s, %s); \n        \"\"\"\n\n    rows = call_stack_overflow_api()\n    for row in rows:\n        row = tuple(row.values())\n        pg_hook = PostgresHook(postgres_conn_id=\"postgres_connection\")\n        pg_hook.run(insert_question_query, parameters=row)\n\n\ndef filter_questions() -> str:\n    \"\"\" \n    Read all questions from the database and filter them.\n    Returns a JSON string that looks like:\n    \n    [\n        {\n        \"title\": \"Question Title\",\n        \"is_answered\": false,\n        \"link\": \"https://stackoverflow.com/questions/0000001/...\",\n        \"tags\": [\"tag_a\",\"tag_b\"],\n        \"question_id\": 0000001\n        },\n    ]\n    \n    \"\"\"\n    columns = (\"title\", \"is_answered\", \"link\", \"tags\", \"question_id\")\n    filtering_query = \"\"\"\n        SELECT title, is_answered, link, tags, question_id\n        FROM public.questions\n        WHERE score >= 1 AND owner_reputation > 1000;\n        \"\"\"\n    pg_hook = PostgresHook(postgres_conn_id=\"postgres_connection\").get_conn()\n\n    with pg_hook.cursor(\"serverCursor\") as pg_cursor:\n        pg_cursor.execute(filtering_query)\n        rows = pg_cursor.fetchall()\n        results = [dict(zip(columns, row)) for row in rows]\n        return json.dumps(results, indent=2)\n\n\ndef write_questions_to_s3():\n    hook = S3Hook(aws_conn_id=\"s3_connection\")\n    hook.load_string(\n        string_data=filter_questions(),\n        key=S3_FILE_NAME,\n        bucket_name=Variable.get(\"S3_BUCKET\"),\n        replace=True,\n    )\n\n\ndef render_template(**context):\n    \"\"\" Render HTML template using questions metadata from S3 bucket \"\"\"\n\n    hook = S3Hook(aws_conn_id=\"s3_connection\")\n    file_content = hook.read_key(\n        key=S3_FILE_NAME, bucket_name=Variable.get(\"S3_BUCKET\")\n    )\n    questions = json.loads(file_content)\n\n    root = os.path.dirname(os.path.abspath(__file__))\n    env = Environment(loader=FileSystemLoader(root))\n    template = env.get_template(\"email_template.html\")\n    html_content = template.render(questions=questions)\n\n    # Push rendered HTML as a string to the Airflow metadata database\n    # to make it available for the next task\n\n    task_instance = context[\"task_instance\"]\n    task_instance.xcom_push(key=\"html_content\", value=html_content)\n\n"
  },
  {
    "path": "requirements.txt",
    "content": "alembic==1.0.11\napache-airflow==1.10.7\napispec==2.0.2\nappdirs==1.4.3\nattrs==19.1.0\nBabel==2.7.0\nblack==19.3b0\nbotocore==1.12.207\ncached-property==1.5.1\ncertifi==2019.6.16\nchardet==3.0.4\nClick==7.0\ncolorama==0.4.1\ncolorlog==4.0.2\nconfigparser==3.5.3\ncroniter==0.3.30\ndefusedxml==0.6.0\ndill==0.2.9\ndocutils==0.14\ndumb-init==1.2.2\nFlask==1.1.1\nFlask-Admin==1.5.3\nFlask-AppBuilder==1.13.1\nFlask-Babel==0.12.2\nFlask-Caching==1.3.3\nFlask-JWT-Extended==3.21.0\nFlask-Login==0.4.1\nFlask-OpenID==1.2.5\nFlask-SQLAlchemy==2.4.0\nflask-swagger==0.2.13\nFlask-WTF==0.14.2\nfuncsigs==1.0.0\nfuture==0.16.0\ngunicorn==19.9.0\nidna==2.8\niso8601==0.1.12\nitsdangerous==1.1.0\nJinja2==2.10.1\njmespath==0.9.4\njson-merge-patch==0.2\njsonschema==3.0.2\nlazy-object-proxy==1.4.1\nlockfile==0.12.2\nMako==1.1.0\nMarkdown==2.6.11\nMarkupSafe==1.1.1\nmarshmallow==2.19.5\nmarshmallow-enum==1.4.1\nmarshmallow-sqlalchemy==0.17.0\nnumpy==1.17.0\nordereddict==1.1\npandas==0.25.0\npendulum==1.4.4\nprison==0.1.0\npsutil==5.6.3\npsycopg2==2.7.7\npsycopg2-binary==2.8.3\nPygments==2.4.2\nPyJWT==1.7.1\npyrsistent==0.15.4\npython-daemon==2.1.2\npython-dateutil==2.8.0\npython-editor==1.0.4\npython3-openid==3.1.0\npytz==2019.2\npytzdata==2019.2\nPyYAML==5.1.2\nrequests==2.22.0\nsetproctitle==1.1.10\nsix==1.12.0\nSQLAlchemy==1.3.6\ntabulate==0.8.3\ntenacity==4.12.0\ntermcolor==1.1.0\ntext-unidecode==1.2\nthrift==0.11.0\ntoml==0.10.0\ntzlocal==1.5.1\nunicodecsv==0.14.1\nurllib3==1.25.3\nWerkzeug==0.15.5\nWTForms==2.2.1\nzope.deprecation==4.4.0\n"
  }
]