<?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 Effy.L.H on Medium]]></title>
        <description><![CDATA[Stories by Effy.L.H on Medium]]></description>
        <link>https://medium.com/@effylh?source=rss-ddb68b63337b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QG6EEodHFn0Rnev8W818dA.jpeg</url>
            <title>Stories by Effy.L.H on Medium</title>
            <link>https://medium.com/@effylh?source=rss-ddb68b63337b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:36:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@effylh/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[Deploy a Flask app with Docker, Google Cloud Run, and Cloud SQL for PostgreSQL database]]></title>
            <link>https://blog.devgenius.io/deploy-a-flask-app-with-docker-google-cloud-run-and-cloud-sql-for-postgresql-6dc9e7f4c434?source=rss-ddb68b63337b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dc9e7f4c434</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[cloud-sql]]></category>
            <dc:creator><![CDATA[Effy.L.H]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 05:53:06 GMT</pubDate>
            <atom:updated>2023-03-09T09:03:30.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*leMSLz0pjkqaiVW2Lr45tw.png" /></figure><ul><li>This deployment guide is based on the project I published before:<strong><em> </em></strong><a href="https://medium.com/@effylh/building-an-online-course-syllabus-scraper-with-flask-udemyapi-postgresql-on-heroku-262b727e228b"><strong><em>Build a web app for generating Markdown syllabus of Udemy with Flask+jQuery+PostgreSQL on Heroku</em></strong></a></li></ul><h4>Application Stack and WorkFlow</h4><ul><li>a brief review of this project</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LrSMG1AK23ZOFs6Kmf_5A.png" /></figure><h4>Preview of the directory structure</h4><p>To implement the dockerization, we should make changes to the directory structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*A7zZbGVwSwG56FqF6xy39A.png" /></figure><h4>Preparations</h4><ul><li>Register an account for the Google Cloud Platform</li><li>Then we need to create a Google Cloud project from the Cloud Console and the <strong>ProjectID</strong></li><li>Register a Docker account and install the Docker Desktop App</li><li>Enable the API of Google Cloud Container Registry</li></ul><h4>Setup the PostgreSQL database on Cloud SQL</h4><p>1. Create a database at Cloud SQL following the steps below:</p><ul><li>Open the Google Cloud Console and navigate to the Cloud SQL section.</li><li>Click on the “Create Instance” button.</li><li>Choose “PostgreSQL” as the database engine.</li><li>Select the desired region and zone for the database.</li><li>Choose the machine type, storage capacity, and other configuration options as per your requirements.</li><li>Enter a name for the instance and set a password for the “postgres” user.</li><li>Click on the “Create” button to create the instance.</li><li>Once the instance is created, click on its name to view the details.</li><li>Click on the “Databases” tab and then click on “Create database”.</li><li>Enter a name for the new database and click on “Create”.</li></ul><p>After creating the instance, we can now check our “<strong>Public IP address</strong>” and “<strong>Connection name</strong>” under the Overview tab on the main page of Cloud SQL, which will be used to connect with our Flask app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFO2Q_EbU9W1uzYWIkVsJA.png" /></figure><p>2. Create a connecter for the Cloud SQL database in our project</p><blockquote>According to Google’s official documentation, there are two approaches for connecting to Cloud SQL:</blockquote><blockquote><strong>* (We choose this approach)</strong>Through <a href="https://cloud.google.com/sql/docs/postgres/connect-run#connect-unix-socket">Unix sockets</a></blockquote><blockquote>* By using a <a href="https://cloud.google.com/sql/docs/postgres/connect-run#connect-connectors">Cloud SQL connector</a></blockquote><p>Let’s create a simplified connecter called<strong><em> connect_unix.py:</em></strong></p><pre>import os<br><br>def get_connect_url():<br>    db_user = os.environ[&quot;DB_USER&quot;]  # e.g. &#39;my-database-user&#39;<br>    db_pass = os.environ[&quot;DB_PASS&quot;]  # e.g. &#39;my-database-password&#39;<br>    db_name = os.environ[&quot;DB_NAME&quot;]  # e.g. &#39;my-database&#39;<br>    if &quot;INSTANCE_UNIX_SOCKET&quot; in os.environ:<br>        unix_socket_path = os.environ[&quot;INSTANCE_UNIX_SOCKET&quot;]  # e.g. &#39;/cloudsql/project:region:instance&#39;<br>        return f&quot;postgresql+pg8000://{db_user}:{db_pass}@/{db_name}?unix_sock={unix_socket_path}/.s.PGSQL.5432&quot;<br>    else:<br>        # Local test<br>        db_host=os.environ[&quot;DB_HOST&quot;]<br>        db_port=os.environ[&quot;DB_PORT&quot;]<br>        return f&quot;postgresql://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}&quot;</pre><p>Pay attention to the format of the database URL for Cloud SQL :</p><pre><br>postgresql+pg8000://&lt;db_user&gt;:&lt;db_pass&gt;@/&lt;db_name&gt;?unix_sock=&lt;INSTANCE_UNIX_SOCKET&gt;/.s.PGSQL.5432</pre><p>3. Update <strong><em>__init__.py</em></strong> for calling the<strong><em> get_connect_url() </em></strong>function<strong><em> </em></strong>defined in<strong><em> connect_unix.py</em></strong></p><pre>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br>import pg8000<br>from project.connect_unix import get_connect_url<br>import os<br><br>app=Flask(__name__)<br># Talisman(app, content_security_policy=None)<br><br>app.config[&quot;SQLALCHEMY_DATABASE_URI&quot;] = get_connect_url()<br>app.config[&quot;SQLALCHEMY_TRACK_MODIFICATIONS&quot;]=False<br><br>db = SQLAlchemy(app)<br><br><br>from project.udemy.views import index_blueprint<br>app.register_blueprint(index_blueprint,url_prefix=&#39;/&#39;)</pre><h4>Dockerize the Flask App</h4><ol><li>For connecting our App with Cloud SQL, we need to add a module called <strong><em>pg8000 </em></strong>in<strong><em> requirements.txt</em></strong></li></ol><pre>Flask-SQLAlchemy==2.5.1<br>psycopg2-binary==2.9.4<br>Flask==2.2.2<br>beautifulsoup4==4.10.0<br>gunicorn==20.1.0<br>requests==2.26.0<br>SQLAlchemy==1.4<br>pg8000</pre><p>2. Create a file called <strong><em>Dockerfile:</em></strong></p><pre>FROM python:3.10.7-slim-buster<br><br># set work directory<br>ENV APP_HOME /app<br>WORKDIR $APP_HOME<br><br># allow statements and log message to immediately appear in the Knative logs<br>ENV PYTHONUNBUFFERED 1<br><br><br># install dependencies<br>RUN pip install --upgrade pip<br>COPY ./requirements.txt .<br>RUN pip install -r requirements.txt<br># copy project<br>COPY . .<br><br>EXPOSE 5000<br><br>CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 run:app</pre><p>3. Set the listen port to default value <strong><em>8080 </em></strong>in<strong><em> run.py:</em></strong></p><blockquote>Official documatation: <a href="https://cloud.google.com/run/docs/container-contract#port">link</a></blockquote><pre>from project import app,db<br>import os<br><br>with app.app_context():<br>    db.create_all()<br><br>if __name__==&#39;__main__&#39;:<br>    app.run(debug=True,host=&quot;0.0.0.0&quot;,port=int(os.envion.get(&quot;PORT&quot;,8080)))</pre><p>4. Create a<strong><em> .dockerignore</em></strong> to exclude files/folders when building the Docker image:</p><pre>.env<br>__pycache__</pre><p>5. Build the Docker image:</p><pre>#inside your Flask App root directory and run the command in your terminal:<br>docker build -t YourDockerAccountName/YourDockerImageName:latest .</pre><p>6. Execute local test by using Docker image:</p><ul><li>Firstly, let’s list all the environment variables we needed for this App:</li></ul><p><strong>(</strong>Udemy API account (click here to apply) will provide you the <strong>ClientID</strong> and <strong>ClientSecret</strong>)</p><pre>udemyClientID=(provided by Udemy API account)<br>udemyClientSecret=(provided b Udemy API account)<br>DATABASE_URL=postgresql://hello_flask:hello_flask@db:5432/hello_flask_prod<br>DB_USER=hello_flask<br>DB_PASS=hello_flask<br>DB_NAME=hello_flask_prod<br>DB_HOST=db<br>DB_PORT=5432<br>PORT=5000</pre><p>We can directly add all environment variables above into the <strong><em>docker run</em></strong> command without defining a <strong><em>.env</em></strong> file seperately:</p><pre>#inside your Flask App root directory and run the command in your terminal:<br>docker run -p 5000:5000 -e DATABASE_URL=postgresql://hello_flask:hello_flask@db:5432/hello_flask_dev -e udemyClientID=YourudemyClientID -e udemyClientSecret=YourudemyClientSecret YourDockerAccountName/YourDockerImageName:latest </pre><p>Now we can access our App in the browser at <strong>localhost:5000;</strong></p><p>Let’s move to the deployment.</p><h4>Deploy to Cloud Run</h4><ol><li>Push Docker image to Docker Hub</li></ol><pre>#inside your Flask App root directory and run the command in your terminal:<br>docker login</pre><pre>#inside your Flask App root directory and run the command in your terminal:<br>docker push YourDockerAccountName/YourDockerImageName:latest</pre><p>2. Push the Docker image from Docker Hub to Container Registry</p><ul><li>Google Cloud will ask you to select a project before using any services. (Do you still remember we created one in the “<strong>Preparations”</strong> section at the beginning of this guide? Choose it!)</li></ul><p>From now on, you can activate the Cloud Shell(a command-line interface) and run these commands below:</p><pre>#set the current active project for the command-line interface<br>gcloud config set project YourGoogleProjectID</pre><ul><li>Enable the Container Registry API service for our Google Cloud project</li></ul><pre>gcloud services enable containerregistry.googleapis.com</pre><ul><li>Then, pull the created Docker image from Docker Hub, tag it, and push it to the Container Registry</li></ul><pre>#run commands below line by line:<br>docker pull YourDockerAccountName/YourDockerImageName:latest<br><br>docker tag YourDockerAccountName/YourDockerImageName:latest gcr.io/syllabus-scraper-378707/YourDockerAccountName/YourDockerImageName:latest<br><br>docker push gcr.io/syllabus-scraper-378707/YourDockerAccountName/YourDockerImageName:latest</pre><p>3. Create a Cloud Run service</p><p>(Note: The settings related to CPU allocation, pricing, etc. may not be suitable for your app, please optimize them according to your specific requirements.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*bT-qR9yzmFcOPsUPAp0nWA.png" /></figure><ul><li>Set environment variables:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*64dZhJc8EtCpMLDR9kG9sA.png" /></figure><p>Q: What’s the value of <strong>INSTANCE_UNIX_SOCKET </strong>above<strong>?</strong></p><ul><li>The format of<strong> INSTANCE_UNIX_SOCKET</strong>: <em>/cloudsql/YourProjectName:YourChoseRegion:YourSQLinstance</em></li></ul><p>Q: How can I find the value of ‘<em>YourProjectName:YourChoseRegion:YourSQLinstance’?</em></p><ul><li>Please search the keyword “<strong>Connection name” </strong>on this page</li></ul><p>Q: Where is the <strong>PORT</strong> environment variable?</p><ul><li>We don’t need to add ‘PORT’ environment variable manually in the Cloud Run service setting page, Cloud Run always set it to 8080. (We add it when we executing <strong><em>docker run</em></strong> command is only for the local testing)</li></ul><p>4. Click the <strong>‘Deploy’</strong> button to deploy our project to Cloud Run</p><p>Now we can access our Flask App via the URL generated by Cloud Run:</p><p>(Of course you can use your own domain instead of the Cloud Run URL for your App)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SrcbbW_XW-1oq5hI1ndsBA.png" /></figure><h3>It works!🥳</h3><p><strong>That’s all for this tutorial. Thanks!</strong></p><p>If you have any questions, feel free to comment.</p><p><strong>App link</strong>: <a href="http://syllabuscraper.com/">syllabuscraper.com</a><br><strong>GitHub repo</strong>:<a href="https://github.com/monkeyapple/Syllabus-Scraper">https://github.com/monkeyapple/Syllabus-Scraper</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dc9e7f4c434" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/deploy-a-flask-app-with-docker-google-cloud-run-and-cloud-sql-for-postgresql-6dc9e7f4c434">Deploy a Flask app with Docker, Google Cloud Run, and Cloud SQL for PostgreSQL database</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a data visualization app for the K-pop TV show ‘Queendom2’ with…]]></title>
            <link>https://blog.devgenius.io/create-a-data-visualization-web-page-with-react-flask-postgresql-bootstrap-4ec4f080309e?source=rss-ddb68b63337b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec4f080309e</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Effy.L.H]]></dc:creator>
            <pubDate>Mon, 09 May 2022 13:55:52 GMT</pubDate>
            <atom:updated>2022-10-26T03:38:41.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create a data visualization app for the K-pop TV show ‘Queendom2’ with React+Flask+PostgreSQL+Bootstrap</h3><p><strong>Web App Link:</strong><a href="https://queendom2.herokuapp.com/">https://queendom2.herokuapp.com/</a><br><strong>GitHub Repo:</strong><a href="https://github.com/monkeyapple/queendom2data">https://github.com/monkeyapple/queendom2data</a></p><h3><strong>Introduction</strong></h3><p>This data visualization app displays the YouTube views count of the ongoing K-pop reality survival show ‘Queendom2’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0E2T0XCD-yvJNIXz4xhUw.png" /></figure><h3>Application Stack and WorkFlow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPmrm_F7gII589_ea5_4YQ.png" /></figure><h3>Tech stack</h3><ul><li><strong>Programming Languages:</strong> Python, Javascript,SQL,CSS,HTML</li><li><strong>Frameworks:</strong>React(Front-end),Flask(Back-end),Bootstrap(CSS)</li><li><strong>Database:</strong>PostgreSQL</li></ul><h3>Preview of our Application</h3><ul><li>This is a single-page web application :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmG4rlGJWNPxZlr6UwJF-Q.png" /></figure><h3>Preview of the project directory structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uye3vPitipFUVv7cXRpbrw.jpeg" /></figure><h3>Preparations</h3><ol><li>Firstly, about the <strong>data scraper </strong>used in<strong> </strong>this project, please check another article I wrote:<a href="https://medium.com/@effylh/create-a-data-scraper-for-the-ongoing-k-pop-tv-program-queendom2-with-python-youtube-data-d74103a3d074">Create a data scraper with Python+YouTube Data API+PostgreSQL+HerokuScheduler</a></li><li>(On Mac)Create and activate a virtual environment <strong><em>queendom </em></strong>and activate it:</li></ol><pre>python3 -m venv <strong><em>queendom</em></strong></pre><p>then, activate the virtual environment we just created:</p><pre>source <strong><em>queendom</em></strong>/bin/activate</pre><p>2. Install needed packages:</p><pre>pip install Flask,Flask-Cors,flask-talisman,gunicorn,psycopg2,python-dotenv</pre><p>3. Create a project folder named <strong>queendom2data </strong>and then <strong><em>cd</em></strong> to the root:</p><pre>(queendom) effylh@192 <strong>queendom2data</strong> %</pre><p>4. Initialize a new React app inside a folder called <strong><em>‘front-end’</em></strong>: (Reference:<a href="https://github.com/facebook/create-react-app">https://github.com/facebook/create-react-app</a>)</p><pre>(queendom) effylh@192 <strong>queendom2data</strong> % npx create-react-app front-end</pre><h3>Let’s get started</h3><p>After we set up our database (which contains two tables) locally in the article(<a href="https://medium.com/@effylh/create-a-data-scraper-for-the-ongoing-k-pop-tv-program-queendom2-with-python-youtube-data-d74103a3d074">link</a>), we can now start to build the back-end framework.</p><h4>Create a class for executing database operations</h4><ol><li>Create a file called <strong>dboperations.py</strong></li><li>Define a class called <strong>DatabaseOperate</strong>, then<strong> </strong>define instance methods <strong>query_table1()</strong> and <strong>query_table2()</strong>, these two methods are used to fetch all data from the existed two tables (<strong>qdscraper_1</strong> &amp; <strong>qdscraper_2</strong>) of the database.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76036f869c507256e48a1392dd3c25c3/href">https://medium.com/media/76036f869c507256e48a1392dd3c25c3/href</a></iframe><h4>Build a Flask Route</h4><ol><li>Create a file called <strong>server.py</strong></li><li>Define a route to tell Flask to use the URL<strong><em> ‘/fetch’ </em></strong>to trigger the function<strong><em> fetch_all_groups()</em></strong></li><li>Inside the <strong><em>fetch_all_groups(): </em></strong>firstly, import the <strong><em>dboperations </em></strong>module and initialize the <strong><em>DatabaseOperate </em></strong>class. Then we use two variables<strong> <em>table1Rows &amp; table2Rows </em></strong>to hold all rows of data fetched from the tables <strong><em>qdscraper_1 </em></strong>and <strong><em>qdscraper_2</em></strong>.</li><li>The <strong>jsonify()</strong> method returns a <strong>Response</strong> object in the format of <em>application/json</em> mimetype.</li><li>Finally, because we want to call the Flask route in React app, we need to import the extension <strong>flask-cors,</strong> then initialize the extension with the default argument<strong> ‘<em>app’, CORS(app),</em></strong> which allows CORS for all domains on all routes.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4740106097644ceefdff11c9a86bfa1d/href">https://medium.com/media/4740106097644ceefdff11c9a86bfa1d/href</a></iframe><h4>Call the Flask route in the React app</h4><ul><li>Import and use <strong>axios</strong> to send the GET request to the Flask route <strong><em>“http://localhost:5000/fetch&quot; , </em></strong>we add a line <strong><em>console.log(rawdata)</em></strong> to check whether we successfully retrieve the data we need.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a369e93c20cfdd0c6205a39ba4ae6f7/href">https://medium.com/media/6a369e93c20cfdd0c6205a39ba4ae6f7/href</a></iframe><p><strong>Outputs: we successfully fetched all data from two tables of the database!</strong></p><blockquote>Notice: Because the scraper of my project keeps inserting new data into the database via the YouTube API while I was writing this article, so the length of data we got in the screenshots might be different with each other in the rest of this article.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0aSDDNieUnIoye7aiHhgA.png" /></figure><h4>Raw Data Processing</h4><ol><li>Create a file called <strong>DataFactory.js,</strong> then define a function called<strong> DataFactory.</strong></li></ol><p>The <strong>DataFactory</strong> returns an object containing a cleaned dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HDKiDlUMv3wiSIEbJpJwA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76a17e971b253faca442b4250ba18fc8/href">https://medium.com/media/76a17e971b253faca442b4250ba18fc8/href</a></iframe><p>2. Call the function <strong>DataFactory</strong> in the <strong>App.js</strong>, then (<strong><em>line 18&amp;19</em></strong>) we set the state and (<strong><em>line 28&amp;29) </em></strong>call the <strong><em>console.log() </em></strong>function to check<strong><em> </em></strong>the<strong><em> </em></strong>values of states we got :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76d221454d4b6a189b16667d3ba5dd7b/href">https://medium.com/media/76d221454d4b6a189b16667d3ba5dd7b/href</a></iframe><p><strong>Outputs:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqtOztKFogOp6URKTotraQ.png" /></figure><h4>Create a Line Chart with Chart.js</h4><ul><li>Create a file called <strong>LineChart.js</strong></li><li>Install the module <strong>“react-chartjs-2”</strong>:(Official Doc:<a href="https://react-chartjs-2.js.org/">https://react-chartjs-2.js.org/</a>)</li></ul><pre>npm install --save chart.js react-chartjs-2</pre><ul><li>Because we need a line chart, so import the<strong> “Line”</strong> module from “react-chartjs-2”,</li><li>The idea of customizing the x-axis ticks are:</li></ul><p>(when the number of data points&gt;100: minor ticks show time in the format of <strong><em>the 12-hour system(AM/PM)</em></strong>),major ticks show dates</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cfQNPUgStMarDWgd7-JVRg.png" /></figure><p>(when the number of data points&gt;1000:x-axis only shows dates)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBHUlaB1TV9DBhF7npgEcg.png" /></figure><p>In order to achieve this goal, we need to use the adapter (we are using <a href="https://github.com/chartjs/chartjs-adapter-date-fns"><strong><em>chartjs-adapter-date-fns</em></strong></a><strong><em> </em></strong>in this project):</p><blockquote>The time scale requires both a date library and a corresponding adapter to be present. Please choose from the <a href="https://github.com/chartjs/awesome#adapters">available adapters </a>.</blockquote><p>Now, Let’s explain the script in the <strong>LineCharts.js:</strong></p><ul><li>The arrow function <strong><em>LineChart contains 2 objects:</em></strong></li></ul><ol><li><strong>options</strong>: customize properties of the chart, such as styling, fonts, the legend, etc.(please check the official doc if you don’t know how to choose those properties:<a href="https://www.chartjs.org/docs/latest/">link</a>)</li><li><strong>data: </strong>define the data structure of the line chart</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daa20af386c9bbdd17ed150c1e41d42c/href">https://medium.com/media/daa20af386c9bbdd17ed150c1e41d42c/href</a></iframe><h4>Create a parent component for the LineChart.js</h4><ol><li>Create a file called <strong>ViewCharts.js</strong></li><li><em>Because the </em><strong><em>likes count </em></strong><em>won’t be released until the end of the TV Show, that’s why we only extract the </em><strong><em>views count </em></strong><em>data </em>as the source dataset for the chart</li><li>Define arrays for each column in the database. Then we use the <strong><em>Array.forEach()</em></strong> function to iterate all the data we got from the scaper: append time values into the <strong><em>labels</em></strong> array, then append <strong><em>views count</em></strong> values into the arrays.</li><li>Return and render the two charts on the screen</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0118dc9c69f5f1ae831288e1b0f183f/href">https://medium.com/media/c0118dc9c69f5f1ae831288e1b0f183f/href</a></iframe><p><strong>Results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMZeq1TSEAXTLSRtg9ssSA.jpeg" /></figure><h4>Styling the page with Bootstrap</h4><ol><li>Install <strong><em>Bootstrap</em></strong> inside the React app folder:</li></ol><pre>npm i -save bootstrap@latest</pre><p>2. Import <strong><em>Bootstrap</em></strong> inside the <strong>index.js</strong> file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rkeqcy-KNFOtQcSX21tBtA.png" /></figure><p>3. Let’s update the script inside the <strong>ViewChart.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce0a28b25599ca304ec88750e2f5632c/href">https://medium.com/media/ce0a28b25599ca304ec88750e2f5632c/href</a></iframe><p><strong>Results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmG4rlGJWNPxZlr6UwJF-Q.png" /></figure><h3>Deployment</h3><p>1. Preparations</p><ul><li>Make sure you already have git installed on your computer.</li><li>Install Heroku CLI: <a href="https://devcenter.heroku.com/articles/heroku-cli">https://devcenter.heroku.com/articles/heroku-cli</a></li><li>(Terminal)activate the virtual environment of your project.</li><li>(Terminal)Log into Heroku:</li></ul><pre>heroku login -i</pre><ul><li>(Terminal)Automatically generate the <strong>requirements.</strong> <strong>txt, </strong>which is a file used to store information about all dependencies of the project:</li></ul><pre>pip freeze &gt; requirements.txt</pre><ul><li>To let Heroku know how to start up our app, we need to create a file called ‘Profile’, then add one line inside of it:</li></ul><pre>web: gunicorn server:app</pre><p><strong><em>server</em></strong>: represents the name of the python file(<strong>server.py</strong>) that runs our app</p><p><strong><em>app</em></strong>: represents the app name, and you can find it inside of the <strong>server.py</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yW7-SOKzFUBDVuD8ljv3pg.png" /></figure><p>2. Set the <strong><em>static_folder</em></strong> path in <strong>server.py:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9YTZ3nSXVgW3SbogO07bA.png" /></figure><p>3. Don’t forget to change the GET request URL from local address to Heroku app address in the <strong>App.js</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IP9_h-FgLBZILcO_HQBomg.png" /></figure><p>4. Also, don’t forget to add a property in the <strong>package.json</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gusS75h81nii9CXLP_SzQ.png" /></figure><p>5. Create a production <strong>build</strong> of your app, run:</p><pre>npm run <strong>build</strong></pre><p>6. Commit changes to the local repository and deploy changes to Heroku</p><pre>git push Heroku main</pre><p><strong>Addition:</strong> If you want to force Flask to use your own domain for the App instead of the one generated by Heroku , you need to install the module called <strong>Talisman, </strong>we need to add one line in the <strong>server.py</strong>:</p><pre>Talisman(app, content_security_policy=None)</pre><p><strong>That’s all for this tutorial. Thanks!</strong></p><p>If you have any questions, feel free to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec4f080309e" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/create-a-data-visualization-web-page-with-react-flask-postgresql-bootstrap-4ec4f080309e">Create a data visualization app for the K-pop TV show ‘Queendom2’ with…</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a data scraper with Python+YouTube Data API+PostgreSQL+HerokuScheduler]]></title>
            <link>https://medium.com/@effylh/create-a-data-scraper-for-the-ongoing-k-pop-tv-program-queendom2-with-python-youtube-data-d74103a3d074?source=rss-ddb68b63337b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d74103a3d074</guid>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Effy.L.H]]></dc:creator>
            <pubDate>Mon, 09 May 2022 09:47:49 GMT</pubDate>
            <atom:updated>2022-05-09T09:56:51.578Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>GitHub repo</strong>:<a href="https://github.com/monkeyapple/queendomscraper_1">https://github.com/monkeyapple/queendomscraper_1</a></p><h3>Motivation</h3><p>As we know, K-pop and Korean pop culture swept the world in recent years, I was trying to step into the field of the K-pop industry and choose some interesting topics to implement data analytics. So as the first step, I decided to create a data scraper for the ongoing K-Pop TV program ‘Queendom2’.</p><h3>Introduction of ‘Queendom2’</h3><ul><li>The program is a comeback battle between 6 K-Pop girl groups</li><li>Episodes release every Thursday on <a href="https://en.wikipedia.org/wiki/Mnet_(TV_channel)">Mnet</a> YouTube official Channel</li><li>We need to collect the each round’s <strong>views count</strong> of performances delivered by all 6 girl groups via <strong><em>YouTube Data API</em></strong></li><li>Red squares below indicate when we insert new data into the database(Note: sometimes it releases 2 performances in one episode, sometimes it releases 3 performances, anyway, there is a total of 6 performances in each round)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sseF_o5tWTiyj-FhwcEcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNMtVxIeZp7dyiVn9bY9uw.png" /></figure><h3>Tech stack</h3><ul><li><strong>Programming Languages:</strong> Python</li><li><strong>Database:</strong>PostgreSQL</li><li><strong>Automation: </strong>HerokuScheduler</li><li><strong>Data API: </strong>YouTube Data API</li></ul><h3>WorkFlow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6biV5V-xzSitKOxoi70fw.png" /></figure><h3>Preview of the directory structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*OpepguxtmTaNuVYaRSb5cA.jpeg" /></figure><h3>Preparations</h3><ol><li>We use Heroku Postgres as our database in this project, so firstly we need to create a new App called<strong> ‘qdscraper’ </strong>on Heroku</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SwxEf7jKEeF075YzlZ-7pA.png" /></figure><p>2. Set up PostgreSQL add on to Heroku server</p><pre>heroku addons:create heroku-postgresql:hobby-dev --app <strong>qdscraper</strong></pre><p>3. Connect to Heroku Postgre database locally</p><p>(If you don’t know how to do it, please check: <a href="https://stackoverflow.com/questions/11769860/connect-to-a-heroku-database-with-pgadmin">link</a>)</p><p>After doing this, we can execute operations of the database locally in pgAdmin</p><h3>Let’s get started</h3><h4>Create tables in the database</h4><ul><li>As the winner of ‘Queendom2’ will be generated in 4 rounds, so we plan to use 4 tables to store the data for each round, and because this is an ongoing program, I will demonstrate how to build 2 of them in this article</li></ul><ol><li>Define two column values for each group in the database: <strong><em>views</em></strong> count &amp; <strong><em>likes </em></strong><em>count</em></li><li>Create two tables <strong>‘qdscraper_1’</strong> and <strong>‘qdscraper_2’ </strong>:</li></ol><pre>CREATE TABLE qdscraper_1 (<br>  id SERIAL PRIMARY KEY,<br>  wjsn_views INTEGER,<br>  wjsn_likes INTEGER,<br>  kep1er_views INTEGER,<br>  kep1er_likes INTEGER,<br>  viviz_views INTEGER,<br>  viviz_likes INTEGER,<br>  hyolyn_views INTEGER,<br>  hyolyn_likes INTEGER,<br>  loona_views INTEGER, <br>  loona_likes INTEGER, <br>  bravegirls_views INTEGER, <br>  bravegirls_likes INTEGER, <br>  update_time TIMESTAMP NOT NULL</pre><pre>)</pre><pre>CREATE TABLE qdscraper_2 (<br>  id SERIAL PRIMARY KEY,<br>  wjsn_views INTEGER,<br>  wjsn_likes INTEGER,<br>  kep1er_views INTEGER,<br>  kep1er_likes INTEGER,<br>  viviz_views INTEGER,<br>  viviz_likes INTEGER,<br>  hyolyn_views INTEGER,<br>  hyolyn_likes INTEGER,<br>  loona_views INTEGER, <br>  loona_likes INTEGER, <br>  bravegirls_views INTEGER, <br>  bravegirls_likes INTEGER, <br>  update_time TIMESTAMP NOT NULL</pre><pre>)</pre><p><strong>Results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljFkigVurTciQVjKayZTaw.png" /></figure><p>3. Define the insert function of the database</p><ul><li>The main goal of this project is fetching data from the API server, then inserting them into the database, we create a file called <strong>db.py</strong>, then define 2 classes and 2 <strong><em>insert_data</em></strong> functions</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/309bf1be4dfd77e423e2e83702a8f510/href">https://medium.com/media/309bf1be4dfd77e423e2e83702a8f510/href</a></iframe><p>Now, let’s move on to the next task: fetching data from YouTube Data API</p><h4>Get data from YouTube Data API</h4><ol><li>Get the key to YouTube Data API. (if you don’t know how to apply it, you can check this video: <a href="https://www.youtube.com/watch?v=TE66McLMMEw">link</a>)</li><li>Create a file called <strong>YTAPI.py, </strong>then define a class with a function called <strong><em>get_video_stats()</em></strong> for fetching data from the YouTube Data API server. (also recommend defining a function called <strong><em>getUrlResponse</em></strong> for reliably<strong><em> </em></strong>sending the <strong>GET</strong> request to the server)</li><li>When you call the API server, besides the key we mentioned in the step1, you also need to provide a <strong><em>video ID </em></strong>to the function, which is actually the last part of the strings in the YouTube URL, here is an example shown below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_pV5wDZi73-VcALyro7TA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf6330b5a85e5e9689fc2173aaea1759/href">https://medium.com/media/bf6330b5a85e5e9689fc2173aaea1759/href</a></iframe><p>4. Create a file called <strong>scraper.py, </strong>don’t forget to import the <strong>YTAPI.py </strong>module we just created. Then call the functions, fetch data from the API server, and execute data cleaning.</p><p>The main purpose of the <strong>scraper.py </strong>is to fetch data from the YouTube API server and insert cleaned data into our database row by row. We get several tasks done in this step:</p><ul><li>As we mentioned before, the format of the URL for making a request to YouTube API is <strong>https://www.googleapis.com/youtube/v3/videos?part=statistics&amp;id={self.video_ids}&amp;key={self.api_key}, </strong>additionally, we can pass in multiple video IDs strings (separate them by comma)into the<strong> {self.video_ids}</strong></li></ul><ol><li>Define a<strong> </strong>dictionary called <strong><em>provide_dict, </em></strong>after we pass video IDs into and call the <strong><em>scrape()</em></strong>, the ID strings will be assigned to the dictionary.</li><li>Because all 6 performances in one round are not released on the same day, so we need to iterate through the dictionary and check whether the ID input is empty, if it is, we just keep the ID as an empty string <strong>‘ ’, </strong>if it’s not<strong>, </strong>we need to assign IDs into the dictionary <strong>video_dict,</strong> and we declare a variable called <strong>video_ids </strong>to hold all the values in a long string format.</li><li>Import the <strong><em>YTAPI</em></strong><em> </em>module, initialize the class <strong><em>YouTubeStats,</em></strong> then call the <strong><em>get_video_stats() </em></strong>function</li><li>Define a dictionary called <strong><em>rowResult </em></strong>and a list called<strong><em> valid_cols. </em></strong>Now we can extract the data from the raw data and append them into the <strong><em>rowResult. </em></strong>We use <strong><em>valid_cols </em></strong>to store all the column names in the database. <strong>(Note:</strong> The <strong>‘likeCount’</strong> will be released until the end of the TV Show, that’s why all the values of <strong>‘likeCount’ </strong>in this article<strong> </strong>are ‘null’ for now .<strong>)</strong></li><li>Don’t forget to add a column called<strong><em> ‘update_time’ </em></strong>that is used to store the current time in the Seoul time zone</li><li>Finally, we can execute the <strong>insert_data()</strong> function</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdaf87fb2e2c3ef686eb8c79d7ca954c/href">https://medium.com/media/bdaf87fb2e2c3ef686eb8c79d7ca954c/href</a></iframe><h4>Execute the application</h4><p>All functional modules are ready, let’s create another <strong>.py</strong> file to run the whole application</p><ul><li>Create a file called <strong>main.py</strong></li></ul><ol><li>Import the<strong><em> db.py</em></strong> module we created before, then initialize the <strong><em>DatabaseOpertions_1</em></strong> and <strong><em>DatabaseOpertions_2</em></strong> classes</li><li>Import <strong><em>os </em></strong>module and use <strong><em>os.environ.get()</em></strong> function for getting the YouTube API key while the App is running(we’ll set config variables in Heroku command-line interface directly later)</li><li>Import the <strong><em>scraper.py</em></strong> module we created before, then initialize the <strong><em>Scraper </em></strong>class with the instances<strong><em> (db_1 </em>and <em>db_2) </em></strong>and<strong><em> </em></strong>YouTube API keys ( If you don’t know how to apply API keys, please check the section <strong><em>‘Get data from YouTube Data API’</em></strong> in this article)</li><li>Call the instance function <strong><em>scrape()</em></strong> with parameters of <strong><em>video IDs </em></strong>( If you don’t know how to get video IDs, please check the section of <strong><em>‘Get data from YouTube Data API’</em></strong> in this article)</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bafd9ab975cc120646fe9984b8852599/href">https://medium.com/media/bafd9ab975cc120646fe9984b8852599/href</a></iframe><h4><strong>Deployment</strong></h4><ul><li>Because we’ve already created the App and set up PostgreSQL on Heroku, we just need to puush our project folders to Heroku via Git:</li></ul><ol><li>(Terminal)Automatically generate the <strong>requirements.</strong> <strong>txt, </strong>which is a file used to store information about all dependencies of the project:</li></ol><pre>pip freeze &gt; requirements.txt</pre><p>2. (Terminal)Log in to Heroku:</p><pre>heroku login -i</pre><p>3. Set up config variables</p><pre>heroku config:set api_key_1=&quot;YOUR YOUTUBE API KEY&quot;<br>heroku config:set api_key_2=&quot;YOUR YOUTUBE API KEY&quot;</pre><p>4. Deploy our project</p><pre>git push heroku main</pre><p>5. Finally, we can run and test our application:</p><pre>heroku open -a syllabuscraper</pre><h4>Implement automation</h4><ul><li>we use HerokuScheduler to execute the cron job every 30 minutes</li></ul><ol><li>Log in to Heroku,</li><li>Head over to the App’s page, then search<strong> ‘Advanced Scheduler’</strong>, and choose the plan which matches your needs.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihX5lekCXYpPJX3fOCIauQ.png" /></figure><p>3. Create Trigger</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4a1ISG4SFSQjuOsUZbC-6g.png" /></figure><p>That’s it! our app will scrape data from YouTube API and inserts new data into the database every 30 mins.</p><h4>Let’s check the results</h4><p><em>(As we mentioned before, the </em><strong><em>likes count </em></strong><em>won’t be released until the end of the TV Show, that’s why all the values of </em><strong><em>‘likeCount’ </em></strong><em>in the database are shown as ‘null’ for now.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FdK1K-yudwwk0iyZU5-itQ.png" /></figure><p><strong>That’s all for this tutorial. Thanks!</strong></p><p>If you have any questions, feel free to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d74103a3d074" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Display recent queries on Web Page from PostgreSql database with Flask+psycopg2+Bootstrap]]></title>
            <link>https://medium.com/pythonistas/display-recent-queries-on-web-page-from-postgresql-database-with-flask-psycopg2-bootstrap-467ced8583c5?source=rss-ddb68b63337b------2</link>
            <guid isPermaLink="false">https://medium.com/p/467ced8583c5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[psycopg2]]></category>
            <dc:creator><![CDATA[Effy.L.H]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 08:27:11 GMT</pubDate>
            <atom:updated>2022-05-11T05:34:37.563Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a simple tutorial for people who is just stepping into Flask framework and trying to display database queries on the screen.</p><p><strong>GitHub repo:</strong><a href="https://github.com/monkeyapple/Display_Queries_With_Flask_psycopg2_Bootstrap">https://github.com/monkeyapple/Display_Queries_With_Flask_psycopg2_Bootstrap</a></p><h3>Sample dataset</h3><p>Here we have a sample database contains a table called ‘game’ which stores 18 games and their last visit records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqh6rGhLOHvUPwKyZOFI-w.png" /></figure><h3>Goal</h3><p>Our goal is to display the 5 most recent queries on the screen</p><h4>Preview of the result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mn0cMd1sc0NTstiJ5ScRg.png" /></figure><h3>Preparations</h3><ol><li>Create an HTML file called <strong>index.html</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e814c3c59e7e8b853497fd154c284204/href">https://medium.com/media/e814c3c59e7e8b853497fd154c284204/href</a></iframe><p>2. Create a file called<strong> run.py, </strong>then define a route to render the <strong>index.html</strong> file we just created</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb8e13346ff600afede3bec85e6ad923/href">https://medium.com/media/fb8e13346ff600afede3bec85e6ad923/href</a></iframe><p>3. Run in the command line and the result is shown as below:</p><pre>python3 run.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOyxqGPJuBQycXFBmEJrkw.png" /></figure><h3>Let’s get started!</h3><h4>Back-End</h4><ol><li>Create a file called <strong>database.ini </strong>in order to safely store database configurations:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd0dfe3e0cc066d943f6a740caf1b8e7/href">https://medium.com/media/fd0dfe3e0cc066d943f6a740caf1b8e7/href</a></iframe><p>2. Create a file called <strong>config.py</strong> in order to safely call the configurations defined inside the <strong>database.ini</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9506cb9b4a3e449e8d872e321e77eb3f/href">https://medium.com/media/9506cb9b4a3e449e8d872e321e77eb3f/href</a></iframe><p>3. Let’s update the <strong>run.py</strong></p><p>1)Import needed modules: <strong>config</strong>(we just created in step 1) , <strong>psycopg2</strong> (psycopg2 is a popular PostgreSQL database adapter )</p><p>2)Connect with our local database by using the <strong>config</strong> module we defined before, then execute a SQL statement to extract the 5 most recent rows from the database(<strong>sort the records according to the ‘last_visit’ column in descending order</strong>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59746ab06bb120d237a34f6d8761022c/href">https://medium.com/media/59746ab06bb120d237a34f6d8761022c/href</a></iframe><p>4. Check the results we got</p><p>The 5 records we need are as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aggtqr1HuUg2DJ46B_l6BQ.png" /></figure><p>The 5 records we actually got:</p><p>(Which means our SQL operations successfully executed!)</p><pre>Outputs:<br>[<br>(4, &#39;The Legend of Zelda: Breath of the Wild&#39;, datetime.datetime(2021, 4, 14, 22, 6, 12)), <br>(3, &#39;Horizon Forbidden West&#39;, datetime.datetime(2021, 4, 5, 2, 43, 2)), <br>(8, &#39;The Elder Scrolls V: Skyrim&#39;, datetime.datetime(2021, 3, 27, 21, 31, 4)), <br>(5, &#39;The Witcher 3: Wild Hunt&#39;, datetime.datetime(2021, 3, 25, 6, 8, 23)), <br>(16, &#39;Final Fantasy&#39;, datetime.datetime(2021, 3, 21, 17, 52, 47))<br>]</pre><p>Since now, we’ve finished all the back-end scripts, let’s move on to the front-end and display the results on the web page:</p><h4>Front-End</h4><ol><li>Add a line at the end of the <strong>index()</strong> function in the<strong> run.py</strong>, the <strong>render_template</strong> method will help us to render the defined <strong>index.html</strong> on the web page, meanwhile, we pass in a variable called <strong>“recentRecords” </strong>and assign the ‘<strong>rowResults’</strong> (query results we retreived from the databse) onto it.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fde77fc6e08e5929b079b8f066abecfb/href">https://medium.com/media/fde77fc6e08e5929b079b8f066abecfb/href</a></iframe><p>2. Render query results <strong>“recentRecords”</strong> by using Jinja’s <strong>for loops</strong> syntax:</p><ul><li>Control flow: if the <strong>“recentRecords” </strong>is equals to<strong> </strong>an empty array<strong> [], </strong>displaying a text “Not enough data” on the screen. Otherwise, displaying a bootstrap table with values we got from the database.</li></ul><p>3. About the style of table, I just simply copy&amp;paste the bootstrap default CSS classes: <strong>“table-hover table-dark table-striped”, </strong>or you can reference the official document to choose what you like: <a href="https://getbootstrap.com/docs/5.1/content/tables/">https://getbootstrap.com/docs/5.1/content/tables/</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5e6e454e58e4d094237816d276bdee7/href">https://medium.com/media/a5e6e454e58e4d094237816d276bdee7/href</a></iframe><h3>Local Test</h3><p>Let’s run the script and access the address <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000</a> on your browser:</p><pre>python3 run.py</pre><h3>It works!🥳</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mn0cMd1sc0NTstiJ5ScRg.png" /></figure><h3>The Real Project Example</h3><p>Another motivation I wrote this tutorial is: I just extended my launched Web App with the same functionality mentioned in this tutorial, which you can check it at:</p><p><strong>App link</strong>: <a href="http://www.syllabuscraper.com/">www.syllabuscraper.com</a><br><strong>And I wrote an article about the Web App:</strong> <a href="https://medium.com/@effylh/building-an-online-course-syllabus-scraper-with-flask-udemyapi-postgresql-on-heroku-262b727e228b?source=your_stories_page----------------------------------------">https://medium.com/@effylh/building-an-online-course-syllabus-scraper-with-flask-udemyapi-postgresql-on-heroku-262b727e228b</a></p><p><strong>That’s all for this tutorial. Thanks!</strong></p><p>If you have any questions, feel free to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467ced8583c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pythonistas/display-recent-queries-on-web-page-from-postgresql-database-with-flask-psycopg2-bootstrap-467ced8583c5">Display recent queries on Web Page from PostgreSql database with Flask+psycopg2+Bootstrap</a> was originally published in <a href="https://medium.com/pythonistas">Pythonistas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a web app for generating Markdown syllabus of Udemy with Flask+jQuery+PostgreSQL on Heroku]]></title>
            <link>https://medium.com/@effylh/building-an-online-course-syllabus-scraper-with-flask-udemyapi-postgresql-on-heroku-262b727e228b?source=rss-ddb68b63337b------2</link>
            <guid isPermaLink="false">https://medium.com/p/262b727e228b</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Effy.L.H]]></dc:creator>
            <pubDate>Sat, 01 Jan 2022 14:07:47 GMT</pubDate>
            <atom:updated>2023-03-07T06:00:30.619Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>App link</strong>: <a href="http://syllabuscraper.com/">syllabuscraper.com</a><br><strong>GitHub repo</strong>:<a href="https://github.com/monkeyapple/Syllabus-Scraper">https://github.com/monkeyapple/Syllabus-Scraper</a></p><h3>Motivation</h3><p>It’s easy to get tired of copying and pasting the syllabus line by line into my notes app when I’m taking courses on Udemy. So I decided to create a web application for automatically scraping syllabuses from the course webpage.</p><h3>Application Stack and WorkFlow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2LrSMG1AK23ZOFs6Kmf_5A.png" /></figure><h3>Preview of our Application</h3><ul><li>This is a single-page web application :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIVAevDm4glaujK3lzZd1Q.png" /></figure><h3>Prerequisites</h3><p>Languages: Python, Javascript(jQuery),CSS,HTML</p><h3>Preparations</h3><ol><li>Create and activate virtual environment folder <strong><em>syllabus</em></strong>:</li></ol><pre>(syllabus)effylh@192 syllabus %</pre><p>2. Install needed packages:</p><pre>beautifulsoup4<br>Flask<br>Flask-Migrate<br>Flask-SQLAlchemy<br>gunicorn<br>psycopg2-binary<br>requests<br>urllib3</pre><p>3. Create a project folder named <strong>Syllabus-Scraper </strong>and then cd to the root:</p><pre>(syllabus) effylh@192 Syllabus-Scraper %</pre><p>4. Create folders we need:</p><pre>(syllabus) effylh@192 Syllabus-Scraper % mkdir project<br>(syllabus) effylh@192 Syllabus-Scraper % cd project<br>(syllabus) effylh@192 Syllabus-Scraper project% mkdir static templates udemy</pre><h3>Preview of the<strong> directory structure</strong></h3><p>When I mention a specified file or folder name in this article, you can come back and check where it’s located in the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*nQwWj9vX52RnUsBamSqv5g.png" /></figure><h3><strong>Let’s get started</strong></h3><p>1. (Backend)Build a skeleton of the Flask app and run it</p><ul><li>Create <strong>run.py</strong>: it will be used to start the application via <strong><em>flask run</em></strong> or <strong><em>python run.py</em></strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2039970cea52075d5c0a85910fe934/href">https://medium.com/media/5d2039970cea52075d5c0a85910fe934/href</a></iframe><ul><li>Create<strong> __init__.py:<em> </em></strong>this file will run automatically as soon as the line <strong><em>from</em></strong> the <strong><em>project import app</em></strong><em> </em>is executed in the <strong>run.py</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96253a0173f8d06946fa861ed68ade9a/href">https://medium.com/media/96253a0173f8d06946fa861ed68ade9a/href</a></iframe><ul><li>Create<strong> view.py</strong>: We need to create two routes for this application</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8241afb97d27e66e672c089ffc3211ee/href">https://medium.com/media/8241afb97d27e66e672c089ffc3211ee/href</a></iframe><ul><li>Furthermore, we can use <strong>Flask-Blueprint</strong> to organize those view functions, which is quite convenient for us to expand more functionalities in the next version. Now let’s make some changes to the <strong>view.py:</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b4cd103d144cc6c6ef9e5a5ba8a76f4/href">https://medium.com/media/6b4cd103d144cc6c6ef9e5a5ba8a76f4/href</a></iframe><ul><li>Also, don’t forget to register the Blueprint in the <strong>__init__.py</strong>:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bc1aa215e5044d640818d40c78038d3/href">https://medium.com/media/8bc1aa215e5044d640818d40c78038d3/href</a></iframe><p>2. (Frontend)Build HTML pages in the <strong>templates</strong> directory</p><ul><li>Create <strong>base.html: </strong>each page in our application will share the same basic layout defined in this HTML file</li><li>In the &lt;head&gt;&lt;/head&gt;block we add all the resources we need for this application: Google Fonts, a link to an external CSS file(we’ll create later), Font Awesome</li><li>{% block content %} {% endblock %} The portion between the two pairs of curly braces can be customized by the contents defined in child templates</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c399eb6982640251bbd3ed29c1c8d03/href">https://medium.com/media/2c399eb6982640251bbd3ed29c1c8d03/href</a></iframe><ul><li>Create <strong>index.html: </strong>as a child template, we can expand the layout based on the <strong>base.html </strong>between {% block content %} and {% endblock %}</li><li>As a reference, here is a wireframing sketched of the index page:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3RQqLJTjBCJFgxqkh3-hQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa2182317af25a7461955c9adc76c75f/href">https://medium.com/media/fa2182317af25a7461955c9adc76c75f/href</a></iframe><ul><li>Then, let’s fill up the wireframing with <a href="https://getbootstrap.com/docs/5.0/getting-started/introduction/">Bootstrap</a> components and the customized CSS file:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a75c0a2f47c1ce021e346e8d4b6904d9/href">https://medium.com/media/a75c0a2f47c1ce021e346e8d4b6904d9/href</a></iframe><ul><li>Create a <strong>styles</strong> folder in the <strong>static</strong> directory,<strong> </strong>then create and put the <strong>index.css </strong>into it.</li></ul><p>The following is the code of the <strong>index.css:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c294c8c2389a3b80e5b9e4eb88ea19b1/href">https://medium.com/media/c294c8c2389a3b80e5b9e4eb88ea19b1/href</a></iframe><ul><li>Thus, we get the result shown as below (The remaining 3 tasks are indicated as well):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDNEflylY8hUYgwIqW_pFA.png" /></figure><p>In the next section, we’re going to create tables and set up a local database in pgAdmin, then we’ll connect the database with our application.</p><h3>ER Model</h3><blockquote><em>ER Model stands for the </em><strong>Entity-Relationship model </strong><em>which is a good way to represent the relationships between each tables of the database.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdirEsfHjNm4pZTjl2wBtw.png" /><figcaption>ER model for this project</figcaption></figure><ol><li>Create a database called <strong>udemy_scrape</strong> in pgAdmin:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*K7yRNys-cjmXwGfuX6gO3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWXmHttpsOXUAnyj8aRraQ.png" /></figure><p>Then, we add some lines in the <strong>__init__.py </strong>in order to<strong> </strong>connect the database with the Flask app:</p><p>2. Import needed packages :</p><ul><li>SQLAlchemy</li><li>Migrate</li><li>os</li></ul><p>3. Use <strong>app.config.from_mapping()</strong> to set configurations for the <strong>app</strong>:</p><ul><li>SECRET_KEY</li><li>SQLALCHEMY_DATABASE_URI</li><li>SQLALCHEMY_TRACK_MODIFICATIONS:</li></ul><p>4. Create an <strong><em>SQLAlchemy</em> </strong>object called <strong>db </strong>and initialize the <strong><em>Flask-Migrate</em></strong> object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91d7425e366f2f07db9587df7c36efea/href">https://medium.com/media/91d7425e366f2f07db9587df7c36efea/href</a></iframe><blockquote>Note1: <em>For local testing:We could assign those configuration variables every time in the terminal , or a more convenient way, we could assign these environment variables (such as</em> <strong><em>‘DATABASE_URL’</em></strong>) <em>inside a file called </em><strong><em>.env</em> </strong><em>(we’ll create it soon)</em></blockquote><blockquote>Note2: <em>For product testing:After deploying all the project files on Heroku, we will assign those configuration variables directly via Heroku </em><strong><em>command-line interface.</em></strong></blockquote><p>5. Create a file called <strong>.env, </strong>then set the environment variable with the <em>URI</em> of our local PostgreSQL database we created before:</p><blockquote>Note: About the general form of PostgreSQL database URI, you can find more details: (Chapter: <strong>34.1.1.2. Connection URIs) : </strong><a href="https://www.postgresql.org/docs/14/libpq-connect.html">https://www.postgresql.org/docs/14/libpq-connect.html</a></blockquote><pre>DATABASE_URL=&quot;postgresql://postgres:854823@localhost:5433/udemy_scrape&quot;</pre><p>6. As the <strong>ER model graph</strong> indicated above, let’s create a file called <strong>models.py</strong>, and<strong> </strong>create two tables inside of it:</p><ul><li><strong>udemy_courselist: a </strong>table storing data related to Udemy platform</li><li><strong>course</strong>: a table storing data of all platforms (We plan to extend functionalities to other platforms such as Coursera and edX in the future.)</li></ul><p>7. We design a <strong>One to One </strong>relationship between these two tables, the following is detailed explanation for the code:</p><ul><li>When the<strong> One to One</strong> relationship is built, the <strong>Course</strong> objects on <strong>UdemyCourseList</strong> called <strong>course</strong></li><li><strong><em>backref</em></strong>: is equivalent to declaring a new property <strong>.udemy_courselist </strong>on the <strong>Course </strong>class. Then we can use any instance of <strong>Course</strong> instead of using the <strong>udemy_course_id</strong> foreign key to access the<strong> UdemyCouseList</strong> model as an object. (For example:<strong>c<em>ourseTableInstance.udemy_courselist</em>)</strong></li><li><strong><em>uselist</em></strong>: because it’s a <strong>one-to-one</strong> relationship, we need to set <strong><em>uselist</em></strong> to <strong>False</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afddfba973530ed6b35d65920a8ee5b4/href">https://medium.com/media/afddfba973530ed6b35d65920a8ee5b4/href</a></iframe><h3>It’s time to build interactive features</h3><p>Our goal is to turn the tasks below into reality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIVAevDm4glaujK3lzZd1Q.png" /></figure><h4>Task1:Collecting submitted link from the user</h4><h4>Task2:Show Markdown results in the text area</h4><h4>Task3:Click the button and check the Markdown live preview</h4><p>Now, let’s create a file called <strong>app.js.</strong></p><ol><li>Create a URI validator:</li></ol><p>In order to get a valid link from the user, we need to create a validator(a javascript function) for the entered link.</p><p>We pick the URL of a random Udemy course and got the general URI pattern as:</p><pre><a href="https://www.udemy.com/course/python-for-machine-learning-data-science-masterclass/">https://www.udemy.com/course/Course-Name-Is-Separated-By-Hyphens/</a></pre><p>Then, we use that pattern to define our validator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28bec5ac4ecd2d7a8db40c4c91220ee9/href">https://medium.com/media/28bec5ac4ecd2d7a8db40c4c91220ee9/href</a></iframe><p>2. Use jQuery to submit the form:</p><blockquote>jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers — <a href="https://jquery.com/">https://jquery.com/</a></blockquote><p>The workflow is like this: After the user enters a link in the input box, clicks the Submit button, triggers the ajax POST request (accessing <strong>views.py</strong> on the server). Then, the script inside the <strong>views.py </strong>begins to check the database, if there is already a record there, retrieve and return it directly; Otherwise, call the UdemyAPI to fetch the data.</p><p>Let’s take a close look at the code below:</p><ul><li>Firstly,We define a function <strong><em>$(‘form’).on(‘submit’, function(e){}</em> </strong>that sets up a ‘submit’ behavior on the form element.</li><li>When the user clicks the button, the string value in the input box with the id of <strong><em>linkInput </em></strong>will assign to the variable <strong><em>inputValue</em></strong><em>.</em></li><li>Then, if the entered link passed the validation check, perform an AJAX request. Otherwise, display an error message.</li><li>Notice:we need to wrap the whole function inside the <strong><em>$( document ).ready()</em>, </strong>which lets the function only run once the page DOM(Document Object Model) is ready.</li><li>Don’t forget to call the <strong><em>preventDefault()</em></strong> method, which prevents the page from reloading the browser whenever a form is submitted.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bba75679cc70500d56c65735d1c36db4/href">https://medium.com/media/bba75679cc70500d56c65735d1c36db4/href</a></iframe><p>3. Before we fill up the jQuery function, we need to get our <strong>index.html</strong> page ready:</p><p>01. Add a Text Area box</p><p>02. Add a ‘Copy’ button</p><p>03. Add a bootstrap collapse component</p><p>04. Add dependencies at the end of the file: bootstrap, showdown(a package used to display Markdown live preview), jQuery; Specify the URL of <strong>app.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a1503a48855ae2c679fdd8cf3bcf4fb/href">https://medium.com/media/3a1503a48855ae2c679fdd8cf3bcf4fb/href</a></iframe><p>4. Now, let’s fill up the rest of the jQuery function:</p><blockquote>We use a set of key/value pairs to configure the Ajax request:</blockquote><ul><li><strong><em>type: </em></strong>set the request type</li><li><strong><em>url: </em></strong>the string<em> </em>URL to which the request is sent.</li><li><strong><em>data: </em></strong>data to be sent to the server (It can be JSON object, string, or array)</li></ul><p><strong>if the validation check is passed:</strong></p><ul><li><strong><em>$.ajax()</em></strong>: make a <strong>POST</strong> request to the URL <strong><em>‘/update’</em></strong> which is defined in the <strong>views.py</strong></li><li><strong><em>req.done()</em></strong>: once the request is complete, the callback function will be invoked</li></ul><p><strong>if the validation check failed:</strong></p><ul><li>display the error message</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b5fb27fc56e96ff1a9e4eba6144b29e/href">https://medium.com/media/7b5fb27fc56e96ff1a9e4eba6144b29e/href</a></iframe><p>5. We also need to build a ‘factory’ for processing the data got by the <strong>app.js</strong>,<strong> </strong>then put those processed data onto the screen by the <strong>update() </strong>function defined in the<strong> views.py</strong></p><p>Firstly, let’s create a new file called <strong>factory.py</strong>, the ‘factory’ stores all the methods we need, let’s check the purpose of each method as follows:</p><ul><li><strong><em>categorize()</em></strong>: We’re planning to extend functionalities to other platforms such as Coursera and edX in the future version, so we use this function to detect all links provided by user and assign each of them a platform code (1 represents Udemy, 2 represents Coursera, etc.)</li></ul><p>The next task is how to get those syllabus data? Creating a webpage scraper might be an option but not recommended here. In fact, all our demands can be satisfied via APIs provided by Udemy, the only thing we need to do is apply an API client account at this page: <a href="https://www.udemy.com/user/edit-api-clients/">https://www.udemy.com/user/edit-api-clients/</a></p><p>When Udemy approved your application, they will provide you a <strong>Client Id</strong> and a <strong>Client Secret</strong> for making requests and retrieving data from their server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dU4quRfuTDrL47QVsN8eyw.png" /></figure><p>Besides, I imported a repository on GitHub as the submodule for my project, which is a quite convenient tool for us to call those API methods(if you have any questions about how to import a existed GitHub repository as your submodule, please check this <a href="https://www.youtube.com/watch?v=gSlXo2iLBro">tutorial</a>):</p><p><a href="https://github.com/r3ap3rpy/udemy">GitHub - r3ap3rpy/udemy: This is the official repository for the package on the pypi.org</a></p><p>In order to get the data we want, firstly, we need to grab the <strong>course id</strong> from the course page, then we make two requests to Udemy server to retrieve the syllabus and the name of that course:</p><ul><li><strong><em>getCourseID()</em></strong></li><li><strong><em>getCourseDetailsFromApi():</em></strong>get the name of the course</li><li><strong><em>getCurriculumFromApi(): </em></strong>get the syllabus of the course</li></ul><p>Below is how the <strong>factory.py </strong>should<strong> </strong>look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cfcdfde5af5d7bd0decf7f6096658d5/href">https://medium.com/media/7cfcdfde5af5d7bd0decf7f6096658d5/href</a></iframe><p>6. It’s time to run our ‘factory’ in the <strong>views.py</strong>, we get several tasks done here:</p><p>01. Grab the link submitted by the user via the ajax POST request</p><p>02. Detect and categorize links according to their platforms</p><p>03. Get the course id from the web page</p><p>04. Check if the course id already exists in our database</p><p>05. If the course id does not exist: make a request to the server to get the syllabus, then add a new record into our database. (If the course id already exists): retrieve and return the data from our database directly</p><p>06. Return course name and syllabus in JSON format</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0145e7e338abad07f3309d087607a8e5/href">https://medium.com/media/0145e7e338abad07f3309d087607a8e5/href</a></iframe><p>7. Then, we’re going to put returned values on the screen, let’s add some lines inside the <strong><em>req.done() </em></strong>function of the <strong>app.js:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ba2d07b3baaae882cfef042f7c13bed/href">https://medium.com/media/3ba2d07b3baaae882cfef042f7c13bed/href</a></iframe><p>In addition, while the user is waiting for the results after clicking the submit button, adding a spinner on the button might be a nice choice, let’s add one line inside the body of the <strong><em>if</em></strong> statement:</p><pre>$(&#39;#submitButton&#39;).html(&#39;&lt;span class=&quot;spinner-border spinner-border-sm&quot; role=&quot;status&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt;Loading...&#39;)</pre><p>We also need to consider the scenario: When our user submits an invalid link and the error message shows up, then they modify and re-submit a valid one, at that moment, the error message should be set back to invisible, right? Let’s add one more line inside the body of <strong><em>if</em></strong> statement:</p><pre>$(&#39;#validateError&#39;).hide()</pre><p>8. Then, We are going to add functionality to the copy button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MK6I627yyduLbcD1DoPXg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d30987ab0844819dfad76efb8a77848/href">https://medium.com/media/2d30987ab0844819dfad76efb8a77848/href</a></iframe><p>This is how the <strong>app.js</strong> should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47d1d253c913e6b346c247b3529be048/href">https://medium.com/media/47d1d253c913e6b346c247b3529be048/href</a></iframe><h3>Local Test</h3><ul><li>Set the FLASK_APP environment variable</li></ul><pre>(Mac)export FLASK_APP=run.py<br>(Win)set FLASK_APP=run.py</pre><ul><li>Implement migration for Flask application(run the code below a line by line)</li></ul><pre>#create a migration repository<br>flask db init</pre><pre>#generate an initial migration<br>flask db migrate -m &quot;AnyMessage&quot; </pre><pre>#apply the migration to the database<br>flask db upgrade</pre><ul><li>Run the application</li></ul><pre>flask run</pre><p>Now, pick a random course and copy its link at the homepage of Udemy, then paste it into our application, click the ‘Submit’ button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*RPuxA4cSdf7fyB2S8Bi48A.gif" /></figure><h3><strong>It works!🥳</strong></h3><h3>(option1)Deploy to Heroku</h3><p><em>Because Heroku ended up with its free tier plan, If you don’t want to use Heroku, please skip this section and directly jump to the next section: Deploy to Google Cloud Run.</em></p><h4>1. Preparations</h4><ul><li>Make sure you already have git installed on your computer.</li><li>Install Heroku CLI: <a href="https://devcenter.heroku.com/articles/heroku-cli">https://devcenter.heroku.com/articles/heroku-cli</a></li><li>(Terminal)activate the virtual environment of your project.</li><li>(Terminal)Log into Heroku:</li></ul><pre>heroku login -i</pre><ul><li>(Terminal)Automatically generate the <strong>requirements.</strong> <strong>txt, </strong>which is a file used to store information about all dependencies of the project:</li></ul><pre>pip freeze &gt; requirements.txt</pre><ul><li>To let Heroku know how to start up our app, we need to create a file called ‘Profile’, then add one line inside of it:</li></ul><pre>web: gunicorn run:app</pre><p><strong><em>run</em></strong>: represents the name of the python file(<strong>run.py</strong>) that runs our app</p><p><strong><em>app</em></strong>: represents the app name, and you can find it inside of the <strong>run.py</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*ZgqxcUyyh0_urqz4de7YyA.png" /></figure><h4>2. Create a Heroku app</h4><p>We can easily create a new app named<strong> ‘syllabuscraper’</strong> on the Heroku web page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g3u_mom1LHf3gURQQdvQvw.png" /></figure><h4>3. Set up PostgreSQL add on to Heroku server</h4><pre>heroku addons:create heroku-postgresql:hobby-dev --app <strong>syllabuscraper</strong></pre><h4>4. Set up config variables</h4><pre>heroku config:set FLASK_APP=run -a <strong>syllabuscraper</strong> <br>heroku config:set SECRET_KEY=&quot;Any_Random_String_Keys&quot; -a <strong>syllabuscraper</strong></pre><h4><strong>5. Deploy our project</strong></h4><pre>git push heroku main</pre><h4>6. Create new tables on Heroku server</h4><pre>heroku run python <br>&gt;&gt;&gt;from project import db <br>&gt;&gt;&gt;db.create_all()</pre><p><strong><em>project: </em></strong>The directory contains the<strong> __init__.py</strong></p><p>Now, we can use a simple line to check whether tables are already there:</p><pre>heroku pg:info -a <strong>syllabuscraper</strong></pre><p>Finally, we can run and test our application:</p><pre>heroku open -a syllabuscraper</pre><h3>(Option2)Deploy to Cloud Run</h3><p>Please Read: <br><a href="https://medium.com/@effylh/deploy-a-flask-app-with-docker-google-cloud-run-and-cloud-sql-for-postgresql-6dc9e7f4c434">Deploy a Flask app with Docker, Google Cloud Run, and Cloud SQL for PostgreSQL</a></p><p><strong>That’s all for this tutorial. Thanks!</strong></p><p>If you have any questions, feel free to comment.</p><p><strong>App link</strong>:<a href="http://syllabuscraper.com/"> syllabuscraper.com</a><br><strong>GitHub repo</strong>:<a href="https://github.com/monkeyapple/Syllabus-Scraper">https://github.com/monkeyapple/Syllabus-Scraper</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=262b727e228b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>