<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Flask Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/flask/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/flask/</link>
	<description></description>
	<lastBuildDate>Mon, 30 Oct 2023 10:39:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Flask Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/flask/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>I Made a ChatGPT-Powered Logo Generator App Using Python Flask in 7 Steps</title>
		<link>https://blog.finxter.com/how-i-created-a-chatgpt-powered-logo-generator-app-using-python-flask/</link>
		
		<dc:creator><![CDATA[Roman Veltman]]></dc:creator>
		<pubDate>Mon, 10 Jul 2023 09:45:20 +0000</pubDate>
				<category><![CDATA[ChatGPT]]></category>
		<category><![CDATA[DALL·E]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1459107</guid>

					<description><![CDATA[<p>In this tutorial, I will show you my step-by-step process of creating a ChatGPT-powered Logo Generator App using Python Flask. This simple but powerful logo generator allows users to quickly generate unique and creative logos for their businesses. Demo Link: https://flask-openai-logo-app.vercel.app/ You can watch my explainer video here as you go through the project: Prerequisites ... <a title="I Made a ChatGPT-Powered Logo Generator App Using Python Flask in 7 Steps" class="read-more" href="https://blog.finxter.com/how-i-created-a-chatgpt-powered-logo-generator-app-using-python-flask/" aria-label="Read more about I Made a ChatGPT-Powered Logo Generator App Using Python Flask in 7 Steps">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-chatgpt-powered-logo-generator-app-using-python-flask/">I Made a ChatGPT-Powered Logo Generator App Using Python Flask in 7 Steps</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this tutorial, I will show you my step-by-step process of creating a <strong>ChatGPT-powered Logo Generator App using Python Flask</strong>. This simple but powerful logo generator allows users to quickly generate unique and creative logos for their businesses.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="802" height="664" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-246.png" alt="" class="wp-image-1459126" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-246.png 802w, https://blog.finxter.com/wp-content/uploads/2023/06/image-246-300x248.png 300w, https://blog.finxter.com/wp-content/uploads/2023/06/image-246-768x636.png 768w" sizes="(max-width: 802px) 100vw, 802px" /></figure>
</div>


<p><strong>Demo Link</strong>: <a rel="noreferrer noopener" href="https://flask-openai-logo-app.vercel.app/" target="_blank">https://flask-openai-logo-app.vercel.app/</a></p>



<p>You can watch my explainer video here as you go through the project:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="How I Made a ChatGPT-Powered Logo Generator App Using Python Flask in 7 Steps" width="937" height="527" src="https://www.youtube.com/embed/XRM60H9atEA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Prerequisites</h2>



<ul class="wp-block-list">
<li>This app uses Python, HTML/CSS, Flask, and the <a href="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/" data-type="post" data-id="1081478" target="_blank" rel="noreferrer noopener">OpenAI API</a> capabilities.</li>



<li>This Finxter Academy course inspired this tutorial: </li>
</ul>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Full Course</strong>: <a rel="noreferrer noopener" href="https://academy.finxter.com/chatgpt-at-the-heart-building-a-movie-recommendation-python-web-app-in-2023/" target="_blank">ChatGPT at the Heart &#8211; Building a Movie Recommendation Python Web App</a></p>



<h2 class="wp-block-heading">Step 1 &#8211; Creating an OpenAI Account</h2>



<p>The first thing I needed to do was to create an OpenAI account. This account allows you to access the <a href="https://blog.finxter.com/python-openai-generate-image-with-dall-e/" data-type="post" data-id="1317762" target="_blank" rel="noreferrer noopener">OpenAI image-creating API</a> I used to generate logos in my Logo Generator App.</p>



<p>Head over to the OpenAI website and create an account and API key.</p>



<p>You can follow the steps from this great Chris tutorial:</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/" data-type="URL" data-id="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/" target="_blank" rel="noreferrer noopener">OpenAI API – or How I Made My Python Code Intelligent</a></p>



<h2 class="wp-block-heading">Step 2 &#8211; Learning about OpenAI Image Creating API</h2>



<p>My next step was to learn to use the OpenAI image-creating API.</p>



<p>Now that you have an OpenAI account and API key let&#8217;s look at how to use the image-creating API.</p>



<p>To generate an image, copy&amp;paste the following code and replace your API key:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import openai

# Your API Key Here:
openai.api_key = 'sk-XXXXXXXXXXXXXXXXXXXXXXXXXXX'

# Your Image Generation Prompt Here:
prompt = "A logo for Fast Delivery service company"

response = openai.Image.create(
    prompt=prompt,
    n=1,
    size="256x256",
)

print(response)
</pre>



<p>Here we set up a request to the OpenAI API and include your API key. The request consists of the word description of the image (prompt), the number of pictures to be generated, and the image size. The OpenAI will use the prompt words to render the images.</p>



<p>The output will be a JSON string like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
  "created": 1686480975,
  "data": [
    {
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-1ax0neSifMwWgCJ8ttPW44Ya/user-TOM2sMmGh0vhOaHhwF18Nb1z/img-JGkInNPRrvZk6oYQROKchxUw.png?st=2023-06-11T09%3A56%3A15Z&amp;se=2023-06-11T11%3A56%3A15Z&amp;sp=r&amp;sv=2021-08-06&amp;sr=b&amp;rscd=inline&amp;rsct=image/png&amp;skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&amp;sktid=a48cca56-e6da-484e-a814-9c849652bcb3&amp;skt=2023-06-10T20%3A42%3A23Z&amp;ske=2023-06-11T20%3A42%3A23Z&amp;sks=b&amp;skv=2021-08-06&amp;sig=SLKkWiM1VjXklnQbABCnVaEtRrUTClH91cfXUpZ50GM%3D"
    }
  ]
}
</pre>



<p>The URL to download the image: <code>response['data'][0]['url']</code></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="256" height="256" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-242.png" alt="" class="wp-image-1459112" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-242.png 256w, https://blog.finxter.com/wp-content/uploads/2023/06/image-242-150x150.png 150w" sizes="(max-width: 256px) 100vw, 256px" /></figure>
</div>


<p>I used the size of 256&#215;256 pixels because it cost less and generated faster.</p>



<h2 class="wp-block-heading">Step 3 &#8211; Choosing a Logo Type</h2>



<p>Before getting into the nitty-gritty of coding, it is essential to understand the basics of logo design.&nbsp;</p>



<p>A logo is a design that embodies an idea or concept intended to identify a business or product. Logos must convey an emotion or sentiment that the viewer can recognize instantly. The design and styling of a logo must be thoughtful and original. A logo must remain memorable and adaptable for various media.</p>



<p>There are many different types of logos. I decided to focus on creating letter mark logos for my Logo Generator App.</p>



<h2 class="wp-block-heading">Step 4 &#8211; Engineering a Prompt for Logo Generation</h2>



<p>A good prompt is critical for the Logo Generator App.</p>



<p><a href="https://blog.finxter.com/annual-income-of-prompt-engineers-in-the-us-chatgpt-a-comprehensive-analysis/" data-type="post" data-id="1261593" target="_blank" rel="noreferrer noopener">Prompt engineering</a> is creating the right combination of words to generate a desired image. This is a crucial step in making our logo generator app because a good prompt will result in a good logo, and there are some basic rules to follow:</p>



<ul class="wp-block-list">
<li>First, the prompt should be as specific as possible so that the AI can generate the desired logo accurately.</li>
</ul>



<p>For example, if you want to generate a logo for a coffee shop, you should include words like &#8220;coffee beans&#8221;, &#8220;mug&#8221;, and &#8220;cafe&#8221;.</p>



<ul class="wp-block-list">
<li>Second, keeping it short and simple is important, as more words will add to the complexity and may result in less accurate results.</li>



<li>Third, you should use descriptive words to create a vivid image.&nbsp;</li>
</ul>



<p>After trying different prompts, I ended with this prompt:</p>



<p><em><code>“A modern, professional-looking, symmetrical, balanced, and centered letter mark logo that incorporates the company name {} in {} color.”</code></em></p>



<h2 class="wp-block-heading">Step 5 &#8211; Writing the Python Flask App Code</h2>



<p>Now that I have my prompt setup, it&#8217;s time to write the code for the Python Flask app.</p>



<p>I assume you have background knowledge of Python and Flask. If not, here is an excellent Chris article about Flask:</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/build-website-with-flask/" data-type="post" data-id="420533" target="_blank" rel="noreferrer noopener">Ten Easy Steps to Your First Python Flask App</a></p>



<p>We want to have the following folder structure for our project.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="388" height="624" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-243.png" alt="" class="wp-image-1459113" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-243.png 388w, https://blog.finxter.com/wp-content/uploads/2023/06/image-243-187x300.png 187w" sizes="auto, (max-width: 388px) 100vw, 388px" /></figure>
</div>


<p>We&#8217;ll start by creating the project folder, a virtual environment, and then install the necessary dependencies.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir flask-openai-logo-app &amp;&amp; cd flask-openai-logo-app

python3 -m venv venv
source venv/bin/activate

pip3 install flask
pip3 install openai
pip3 install urllib3==1.26.6
pip3 install python-dotenv

pip3 freeze > requirements.txt
</pre>



<p>Next, we create a <code>.env</code> file.</p>



<p class="has-base-2-background-color has-background"><strong>Note</strong>: it is important to remember to remove your API key from <code>.env</code> before making your project public!</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">FLASK_APP=openai-logo-app/app.py
FLASK_DEBUG=1
OPENAI_API_KEY=sk-XXXXXXXXXXXXXXXXXXXXXXXXXXX</pre>



<p>Now it’s time to create the <code>app.py</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import openai
from flask import Flask, render_template, request


app = Flask(__name__)
openai.api_key = os.getenv("OPENAI_API_KEY")




@app.route("/", methods=("GET", "POST"))
def openai_app():
    if request.method == "POST":
        text = request.form["text"]
        color = request.form["color"]
        number = request.form["number"]
        response = openai.Image.create(
            prompt=generate_prompt(text, color),
            n=min(int(number), 5),
            size="256x256"
        )


        return render_template("index.html", result=response)


    return render_template("index.html")




def generate_prompt(text, color):
    return "Modern, symmetrical, balanced, centered, professional-looking, letter mark logo that incorporates the " \
           "company name: \"{}\", {} color.".format(text, color)




if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5050)
</pre>



<p>It contains the code that defines the ‘<code>/</code>’ endpoint, makes a request to the OpenAI API, and includes a function that generates the prompt based on the parameters we will get in an HTML form from the user.</p>



<h2 class="wp-block-heading">Step 6 &#8211; Creating a Form (HTML &amp; CSS)</h2>



<p>Now, we want to create a simple form so users can customize the logo they want to make.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="777" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-244-1024x777.png" alt="" class="wp-image-1459114" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-244-1024x777.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/06/image-244-300x228.png 300w, https://blog.finxter.com/wp-content/uploads/2023/06/image-244-768x583.png 768w, https://blog.finxter.com/wp-content/uploads/2023/06/image-244.png 1202w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>The form asks the user to fill in 3 fields: Color, Brand Name, and Number of images to be generated and has a &#8220;GENERATE LOGO&#8221; button to submit the form.</p>



<p>To do this, I created an HTML page with the form.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;head>
  &lt;title>OpenAI Logo Maker&lt;/title>
  &lt;link
    rel="shortcut icon"
    href="{{ url_for('static', filename='icon.jpg') }}"
  />
  &lt;link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" />
  &lt;script src="https://code.jquery.com/jquery-3.7.0.min.js">&lt;/script>
  &lt;script type="text/javascript">
    function loading(){
      $(".loading").show();
    }
  &lt;/script>
&lt;/head>

&lt;body>
  &lt;img src="{{ url_for('static', filename='icon.jpg') }}" class="icon" />
  &lt;h3>Generate a Lettermark logo&lt;/h3>
  &lt;form action="/" method="post">
    &lt;input type="text" name="color" placeholder="Enter the logo color, e.g. dark gold" required />
    &lt;input type="text" name="text" placeholder="Enter the brand name, e.g. Fast Delivery" required />
    &lt;input type="text" name="number" placeholder="How many proposals, e.g. 1,2,...,5" required />
    &lt;input type="submit" value="GENERATE LOGO" onclick="loading();" />
  &lt;/form>
  {% if result %}
  &lt;div class="result">
    {%for i in result['data']%}
      &lt;img src={{i['url']}}>
    {%endfor%}
  &lt;/div>
  {% endif %}
  &lt;div class="loading">
    &lt;img src="{{ url_for('static', filename='loading.jpg') }}" width="35" height="35">
  &lt;/div>
&lt;/body>
</pre>



<p>A lot of things are going on here.</p>



<p>First, I use a simple JS script based on the jquery library to show a “Loading…” animation after the user clicks the &#8220;GENERATE LOGO&#8221; button.</p>



<p>Second, I define the form input fields with placeholders with instructions for the user.</p>



<p>Lastly, the <code>{{ … }}</code> placeholder displays dynamic content in the template file. Flask depends on the Jinja2 template engine, so when <code>render_template()</code> is called, it equally calls the Jinja2 template engine, which substitutes the <code>{{ … }}</code> block with the values provided in the <code>render_template()</code> function.</p>



<p>In addition, I added a basic CSS styling file to make the form look presentable.</p>



<h2 class="wp-block-heading">Step 7 &#8211; Getting and Displaying Images from OpenAI</h2>



<p>When a user submits the form, the app requests the OpenAI API to get the selected image. The image is stored on the server, and a URL is generated.</p>



<p>I use Jinja2 support of conditional statements and for–loops inside the <code>{% … %}</code> blocks, and if the result variable is given, we get the created image&#8217;s URLs and display them.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="726" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-245-1024x726.png" alt="" class="wp-image-1459118" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-245-1024x726.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/06/image-245-300x213.png 300w, https://blog.finxter.com/wp-content/uploads/2023/06/image-245-768x545.png 768w, https://blog.finxter.com/wp-content/uploads/2023/06/image-245-1536x1090.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/06/image-245.png 1600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h2 class="wp-block-heading">Conclusion</h2>



<p>Congratulation we have successfully come to the end of the tutorial!</p>



<p>Creating a Logo Generator App with OpenAI’s API and Python Flask was a fun and educational task.&nbsp;</p>



<p>I hope this tutorial was helpful and that you can create a logo generator application of your own.</p>



<p>Feel free to comment below if you have any questions or feedback.</p>



<p>The complete code is available on my GitHub page: <a href="https://github.com/rommanve/flask-openai-logo-app" target="_blank" rel="noreferrer noopener">https://github.com/rommanve/flask-openai-logo-app</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-chatgpt-powered-logo-generator-app-using-python-flask/">I Made a ChatGPT-Powered Logo Generator App Using Python Flask in 7 Steps</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Created a Face-Detection App Using the Flask Framework</title>
		<link>https://blog.finxter.com/how-i-created-a-face-detection-app-using-the-flask-framework/</link>
		
		<dc:creator><![CDATA[Jonathan Okah]]></dc:creator>
		<pubDate>Sun, 18 Jun 2023 12:44:09 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[OpenCV]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1448181</guid>

					<description><![CDATA[<p>Advancement in technology has witnessed the application of artificial intelligence to detect and recognize human faces. 👩👩‍🦲👨‍🦰 This is accomplished using OpenCV, a Python library for computer vision and image processing. In the previous tutorials, we use OpenCV to process images and turn them into pencil drawings and cartoons. We will learn how to use ... <a title="How I Created a Face-Detection App Using the Flask Framework" class="read-more" href="https://blog.finxter.com/how-i-created-a-face-detection-app-using-the-flask-framework/" aria-label="Read more about How I Created a Face-Detection App Using the Flask Framework">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-face-detection-app-using-the-flask-framework/">How I Created a Face-Detection App Using the Flask Framework</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Advancement in technology has witnessed the application of artificial intelligence to <strong>detect and recognize human faces</strong>. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469.png" alt="👩" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f9b2.png" alt="👩‍🦲" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f468-200d-1f9b0.png" alt="👨‍🦰" class="wp-smiley" style="height: 1em; max-height: 1em;" /> This is accomplished using <a href="https://blog.finxter.com/motion-detection-using-opencv-in-python-my-journey-through-to-a-successful-project/" data-type="post" data-id="1153887" target="_blank" rel="noreferrer noopener">OpenCV</a>, a Python library for computer vision and image processing.</p>



<p>In the previous tutorials, we use OpenCV to process images and turn them into <a rel="noreferrer noopener" href="https://blog.finxter.com/how-i-created-a-sketch-making-app-using-flask/" data-type="post" data-id="1410953" target="_blank">pencil drawings</a> and <a href="https://blog.finxter.com/how-i-created-a-sketch-and-cartoon-making-app-using-flask/" data-type="post" data-id="1413239" target="_blank" rel="noreferrer noopener">cartoons</a>. We will learn how to use the same library to detect human faces on images and render them on a Flask web application.</p>



<p>For our application to be able to detect a human face, it needs to be trained on large amounts of data that contain a sufficient representation of people from different backgrounds. This requires long hours of model training, and we don’t have all day for such a time-consuming task.</p>



<p>Thanks to the OpenCV library that comes with its trained models for face detection. All that we need to do is to use the algorithm to detect faces in our applications.</p>



<h2 class="wp-block-heading">The Haar-Cascade Algorithm</h2>



<p>The Haar-Cascade algorithm is a machine-learning model trained to detect objects in images. It can run in real-time. <strong><em>Haar-Cascade are nothing but XML files used in OpenCV to detect specified objects.</em></strong> It can detect various objects like buildings, eyes, noses, fruits, cars, mouths and bikes.</p>



<p>Depending on the object you want to detect, you first have to load the pre-trained XML files, if, of course, it’s available. To learn more about Haar-Cascades, check <a href="https://medium.com/analytics-vidhya/haar-cascades-explained-38210e57970d" data-type="URL" data-id="https://medium.com/analytics-vidhya/haar-cascades-explained-38210e57970d" target="_blank" rel="noreferrer noopener">this article</a> on Medium.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="578" height="330" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-149.png" alt="" class="wp-image-1448204" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-149.png 578w, https://blog.finxter.com/wp-content/uploads/2023/06/image-149-300x171.png 300w" sizes="auto, (max-width: 578px) 100vw, 578px" /></figure>
</div>


<h2 class="wp-block-heading">Using OpenCV for face detection</h2>



<p>Let’s see how to use OpenCV for face detection. I will be using a particular picture for this demonstration. Feel free to use any picture of your choice. Create and move into a new folder for this project. Install <code><a href="https://blog.finxter.com/how-to-install-opencv-on-pycharm/" data-type="post" data-id="35085" target="_blank" rel="noreferrer noopener">opencv-python</a></code> if you haven’t done so.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install opencv-python</pre>



<p>Import the library and define the path to the image.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import cv2 as cv

image = 'Jonaben.jpg'
</pre>



<p>Make sure you have this image in your current folder. Let’s read the image using the <code><a href="https://blog.finxter.com/matplotlib-imshow/" data-type="post" data-id="6487" target="_blank" rel="noreferrer noopener">imread()</a></code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">img = cv.imread(image)</pre>



<p>The image is returned as a <a href="https://blog.finxter.com/numpy-array-slicing/" data-type="post" data-id="985316" target="_blank" rel="noreferrer noopener">NumPy array</a>. Let’s see the shape of the image.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">img.shape
(2560, 1920, 3)
</pre>



<p>The image is a three-dimensional array representing the height width and channels respectively. The three channels represent blue, green and red (BGR) colors as used in OpenCV.</p>



<p>Let’s convert the image to grayscale before performing face detection on it.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)</pre>



<p>If you check the shape again, you will notice that it is now a 2-dimensional image as the color channel has been removed. Let’s now load call the Haar-Cascade algorithm.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">face_classifier = cv.CascadeClassifier(
    cv.data.haarcascades + "haarcascade_frontalface_default.xml"
)
</pre>



<p>The <code>haarcascade_frontalface_default.xml</code> is a classifier for face detection. For other object detection classifiers, check <a rel="noreferrer noopener" href="https://github.com/opencv/opencv/tree/master/data/haarcascades" data-type="URL" data-id="https://github.com/opencv/opencv/tree/master/data/haarcascades" target="_blank">this repository</a>.<sup> </sup>We will now perform face detection using the classifier.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">face = face_classifier.detectMultiScale(
    gray, scaleFactor=1.1, minNeighbors=5, minSize=(40, 40)
)
</pre>



<p>The <code>detectMultiscale()</code> method will be used to identify faces of different sizes. The <code>scaleFactor</code> reduces the grayscale to 10% of the original sizes to accommodate faces of different scales. The <code>minNeighbors</code> parameter defines the number of neighbors each rectangle should have.</p>



<p>A higher value will give high quality but few detections. By specifying 5, we try to strike a balance between quality and quantity. The <code>minSize</code> is the minimum size a face should have. Any face less than that is completely ignored.</p>



<p>Now that the face is detected, let’s draw a rectangle over the detected face.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for (x, y, w, h) in face:
    cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4)
</pre>



<p>The face is represented as a <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank" rel="noreferrer noopener">tuple</a> consisting of x and y coordinates, width and height. We perform a <code>for</code> loop which iterates over the face and uses the <code>rectangle()</code> function to draw a green rectangle over the face using the coordinates and dimensions of the face. The value (0, 255, 0) is the green color and 4 is the thickness in pixels.</p>



<p>To display the image, we first have to turn it into RGB color format. Then, we use the <code>matplotlib</code> library to display the image</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">rgb_img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
plt.figure(figsize=(20,10))
plt.imshow(rgb_img)
plt.axis('off')
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="219" height="213" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-150.png" alt="" class="wp-image-1448217"/></figure>
</div>


<h2 class="wp-block-heading">Integrating Face Detection in Flask Application</h2>



<p>We will create a Flask application to display the image faces detected by OpenCV. It will be similar to the <a href="https://blog.finxter.com/how-i-created-a-sketch-making-app-using-flask/" data-type="post" data-id="1410953" target="_blank" rel="noreferrer noopener">sketch-making Flask application</a> we created previously but with a few modifications. Therefore, you are required to go through that tutorial to understand how we created the application.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="713" height="401" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-151.png" alt="" class="wp-image-1448218" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-151.png 713w, https://blog.finxter.com/wp-content/uploads/2023/06/image-151-300x169.png 300w" sizes="auto, (max-width: 713px) 100vw, 713px" /></figure>
</div>


<p>This is because I don’t want to repeat myself here to avoid bloating this article. &nbsp;I will only show you what to do on the command line.</p>



<p>In your current folder, create two files: a folder (app by name) and a <code>run.py</code> file. Move inside the app folder.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir app &amp;&amp; touch run.py
cd app</pre>



<p>Inside the <code>app</code> folder, create a file, <code>capture.py</code> (for Linux users, use <code>nano capture.py</code> on the command line) and write the following in it:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import cv2 as cv

def image_capture(img):
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    face_classifier = cv.CascadeClassifier(
        cv.data.haarcascades + "haarcascade_frontalface_default.xml"
)
    face = face_classifier.detectMultiScale(
       gray, scaleFactor=1.1, minNeighbors=5, minSize=(40,40)
    )
    for (x, y, w, h) in face:
        cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4)

    rgb_img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    return rgb_img
</pre>



<p>This is exactly what we just did. It’s now wrapped in a function. Next, create an <code>__init__.py</code> and write the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from flask import Flask
from secrets import token_hex


UPLOAD_FOLDER = 'app/static/uploads'
SECRET_KEY = token_hex(16)


app = Flask(__name__)

app.config['SEND_FILE_MAXIMUM_AGE_DEFAULT'] = 0
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = SECRET_KEY


from app import main
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="713" height="401" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-152.png" alt="" class="wp-image-1448219" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-152.png 713w, https://blog.finxter.com/wp-content/uploads/2023/06/image-152-300x169.png 300w" sizes="auto, (max-width: 713px) 100vw, 713px" /></figure>
</div>


<p>Go through that article to understand what these configurations mean. Now, create a <code>file.py</code> file, and write the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.')[1] in ALLOWED_EXTENSIONS
</pre>



<p>Next, the <code>main.py</code> file. Create it inside the <code>app</code> folder. Then, write these:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import cv2
import os
from werkzeug.utils import secure_filename
from flask import request, render_template
from app import app
from app.file import allowed_file
from app.capture import image_capture



UPLOAD_FOLDER = 'app/static/uploads'
CAPTURE_FOLDER = 'app/static/capture'


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/capture', methods=['GET', 'POST'])
def sketch():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename =secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        img = cv2.imread(UPLOAD_FOLDER+'/'+filename)
        capture_img = image_capture(img)
        capture_img_name = filename.split('.')[0]+'_capture.jpg'
        save = cv2.imwrite(CAPTURE_FOLDER+'/'+capture_img_name, capture_img)
        return render_template('home.html', org_img_name=filename, capture_img_name=capture_img_name)
    return render_template('home.html')
</pre>



<p>I made some modifications to that project article to correspond with what we are learning in this tutorial. The image, when uploaded, will go to a static folder as static file. Therefore, create the folder and inside the static folder, create two more folders.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir -p static/uploads static/capture static/css</pre>



<p>We also create a <code>css</code> folder for CSS files. So, once the uploaded file is received, it will be stored in the <code>uploads</code> folder. Then, we use OpenCV to read it and call the <code>image_capture()</code> for face detection.</p>



<p>The result is now stored in the capture folder and displayed in the Flask application.</p>



<p>On the terminal, create a <code>home.html</code> file. It will be inside the <code>templates</code> folder.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">nano templates/home.html</pre>



<p>Write the following in it:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html lang="en">

&lt;head>
    &lt;!-- Required meta tags -->
    &lt;meta charset="utf-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1">
    &lt;!-- Bootstrap CSS -->
    &lt;link rel="stylesheet" href="static/css/styles.css">
    &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    &lt;title>Face Detection&lt;/title>
&lt;/head>

&lt;body style="background:pink">

    &lt;div class='regform mt-3'>
        &lt;h1 style="text-align:center;">Flask Face Detection App&lt;/h1>
    &lt;/div>

    &lt;form action='/capture' class='main-form' method="POST" enctype="multipart/form-data">

        &lt;div class='text-center'>
            &lt;input type="file" id="file" name='file' style="margin-top:10px;margin-bottom:10px;">
            &lt;button type='submit' class='btn btn-outline-success'> Capture
            &lt;/button>
        &lt;/div>

    &lt;/form>

    {% if capture_img_name %}
    &lt;div class="row" style="margin-top:10px;margin-bottom:10px;">
        &lt;div class="col text-center">
            &lt;h2>Original Image&lt;/h2>&lt;img src='static/uploads/{{ org_img_name }}'
                style="display: block;margin-left: auto;margin-right: auto;">
        &lt;/div>
        &lt;div class="col text-center">
            &lt;h2>Captured Image&lt;/h2>&lt;img src='static/capture/{{ capture_img_name }}'
                style="display:block;margin-left: auto;margin-right: auto;"> &lt;/div>
    &lt;/div>
    {% endif %}

&lt;/body>
&lt;/html>
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="713" height="401" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-153.png" alt="" class="wp-image-1448222" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-153.png 713w, https://blog.finxter.com/wp-content/uploads/2023/06/image-153-300x169.png 300w" sizes="auto, (max-width: 713px) 100vw, 713px" /></figure>
</div>


<p>In your <code>css</code> folder, create a <code>styles.css</code> file:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">body {
     font-family: sans-serif;
     margin-top: 40px;
}

   .regform {
     width: 800px;
     margin: auto;
     color: black;
     padding: 10px, 0px, 10px, 0px;
     text-align: center;
     border-radius: 15px, 15px, 0px, 0px;
}


   .main-form {
     width: 800px;
     margin: auto;
     padding-left: 50px;
     padding-right: 50px;
     color: #ffffff;
}

   img {
     max-height: 400px;
     max-width: 500px;
     height: auto;
     width: auto;
}
</pre>



<p>Finally, in your <code>run.py</code> file, write this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from app import app


if __name__ == '__main__':
    app.run()
</pre>



<p>To start the local server, move into your project folder and type <code>flask run</code><em> </em>in the terminal.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>In this project, we have learned how to create a face-detection app using OpenCV and the Flask framework. Use this knowledge to improve your Python skills. Check my <a href="https://github.com/finxter/flask_face_detection_app" data-type="URL" data-id="https://github.com/finxter/flask_face_detection_app" target="_blank" rel="noreferrer noopener">GitHub page</a> for the source code.</p>



<p>We can take this app further perhaps, to add real-time face detection. Furthermore, we can create a face recognition app and render it on a Flask application. I may give attention to that in future project tutorials. </p>



<p>Thanks for staying with me throughout this tutorial. Enjoy your day!</p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-face-detection-app-using-the-flask-framework/">How I Created a Face-Detection App Using the Flask Framework</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Created an Email Address Verifier Using Flask</title>
		<link>https://blog.finxter.com/how-i-created-an-email-address-verifier-using-flask/</link>
		
		<dc:creator><![CDATA[Jonathan Okah]]></dc:creator>
		<pubDate>Fri, 12 May 2023 07:42:19 +0000</pubDate>
				<category><![CDATA[Flask]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Streamlit]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1354875</guid>

					<description><![CDATA[<p>Email addresses are primarily used for communication. They are also used for authentication and authorization. Collecting email addresses is crucial for marketing companies and other businesses. It helps to promote their services and to provide good customer support. ✅ Verification of email addresses involves confirming the authenticity or legitimacy of user&#8217;s email address. Integrating email ... <a title="How I Created an Email Address Verifier Using Flask" class="read-more" href="https://blog.finxter.com/how-i-created-an-email-address-verifier-using-flask/" aria-label="Read more about How I Created an Email Address Verifier Using Flask">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-an-email-address-verifier-using-flask/">How I Created an Email Address Verifier Using Flask</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Email addresses are primarily used for communication. They are also used for authentication and authorization. Collecting email addresses is crucial for marketing companies and other businesses. It helps to promote their services and to provide good customer support.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Verification of email addresses</strong> involves confirming the authenticity or legitimacy of user&#8217;s email address. Integrating email verification in signup forms will ensure businesses have customer email addresses that are valid and reachable.</p>



<p>Notice the expression, <em>&#8216;valid and reachable.&#8217;</em> This means an email can be valid but not reachable.</p>



<h2 class="wp-block-heading">How to Verify Email Addresses?</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="595" height="893" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-125.png" alt="" class="wp-image-1354893" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-125.png 595w, https://blog.finxter.com/wp-content/uploads/2023/05/image-125-200x300.png 200w" sizes="auto, (max-width: 595px) 100vw, 595px" /></figure>
</div>


<p>There are several ways to check if an email address is valid and in existence.</p>



<p><strong>Method 1</strong>: We can use a <a rel="noreferrer noopener" href="https://blog.finxter.com/what-are-regular-expressions-used-for-10-applications/" data-type="post" data-id="6504" target="_blank">Regular Expression</a>. The <code>re</code> Python module has <a rel="noreferrer noopener" href="https://blog.finxter.com/python-regex-search/" data-type="post" data-id="5749" target="_blank"><code>search</code></a> and <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-regex-match/" data-type="post" data-id="5759" target="_blank">match</a></code> methods that return an object that matches the given pattern. </p>



<p>Regular Expression, though it works in most cases cannot be relied on to verify the authenticity of email addresses. And if you are like me who struggles to understand Regular Expression, you probably won&#8217;t consider it an ideal one to use.</p>



<p>What is more, Regular Expression only checks email formats but not their existence. You may want to try other ways of verifying email addresses.</p>



<p><strong>Method 2</strong>: Another way to verify an email address is to use a Python package, <code>validate-email-address</code>. It also uses the <code>re</code> module to check if the email address is properly formatted, and a third-party Python package, <code>py3dns</code> to ensure it is active. </p>



<p>Here is a simple way to use the module:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from validate_email_address import validate_email
isValid = validate_email('melancholy@gmail.com', verify=True)
print(isValid)</pre>



<p>If that email exists, it will print out <code>True</code>.</p>



<p><strong>Method 3</strong>: The best and recommended way to verify an email address is by using an API. Dedicated third-party APIs such as <em>emailvalidation.io</em> provide a secure and reliable way to verify an email address.</p>



<p>In this project tutorial, we are going to implement such a feature in a Flask application. Go to the <a href="https://app.emailvalidation.io/" data-type="URL" data-id="https://app.emailvalidation.io/" target="_blank" rel="noreferrer noopener">website</a>, register with your email and password. Log in and you will see your API key. We will use the API key in our Flask application.</p>



<h2 class="wp-block-heading">Creating a Flask Application</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="920" height="613" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-126.png" alt="" class="wp-image-1354895" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-126.png 920w, https://blog.finxter.com/wp-content/uploads/2023/05/image-126-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/05/image-126-768x512.png 768w" sizes="auto, (max-width: 920px) 100vw, 920px" /></figure>
</div>


<p>Create and activate a <a href="https://blog.finxter.com/python-virtual-environments-with-venv-a-step-by-step-guide/" data-type="post" data-id="3393" target="_blank" rel="noreferrer noopener">virtual environment</a> in a new folder. Then, install the Flask package. Next, create a <code>templates</code> folder. Inside the folder, create <code>base.html</code> and <code>index.html</code> files. </p>



<p>For the <code>base.html</code> file, write the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html lang="en">
&lt;head>
    &lt;meta charset="UTF-8">
    &lt;meta http-equiv="X-UA-Compatible" content="IE=edge">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Flask Email Verifier&lt;/title>
    &lt;link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet">
&lt;/head>
&lt;body style="background-color:rgb(248, 244, 244)">
    {% block content %}

    {% endblock %}
    &lt;script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js">&lt;/script>
&lt;/body>
&lt;/html>
</pre>



<p>The <code>index.html</code> will inherit everything in the <code>base.html</code>. Write this inside the file:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!-- extends is for inheriting from the base.html -->
{% extends 'base.html' %}
{% block content %}
&lt;div class="row justify-content-center my-5">
          &lt;div class="col-md-5 mt-4">
              &lt;div class="card">
                  &lt;h3 class="card-header">Email Verifier&lt;/h3>
                  &lt;div class="card-body">
                    &lt;form action="." method="POST">
                      
                      &lt;div class="input-group">
                        &lt;input type="text" required class="form-control" name="email-address" placeholder="Enter an email address to verify it">
                        &lt;div class="input-group-append">
                          &lt;button class="btn btn-primary fw-bold" type="submit">
                            Verify
                          &lt;/button>
                        &lt;/div>
                      &lt;/div>
                    &lt;/form>
                      &lt;hr>
                      {% if response %}
                      &lt;p>{{ response }}&lt;/p>
                     {% endif %}

{% endblock %}
</pre>



<p>Let&#8217;s write a function that sends a request to the API. Save the following script as <code>email_verifier.py</code> in your project folder:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests
from decouple import config

API_KEY = config('secret_key')


def is_valid_email(email):
    url = f"https://api.emailvalidation.io/v1/info?email={email}&amp;apikey={API_KEY}"
    response = requests.get(url)
    if response.status_code == 200:
         json_res = response.json()
         format_valid = json_res['format_valid']
         mx_found = json_res['mx_found']
         smtp_check = json_res['smtp_check']
         state = json_res['state']
         return format_valid and mx_found and smtp_check and state == 'deliverable'
    return False
</pre>



<p>We import the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library/" data-type="post" data-id="37796" target="_blank">requests</a></code> module to be used to make a request to the API. We also import <code>python-decouple</code> module to load environment variables. So, you have to install these modules together with <code>python-dotenv</code> in your virtual environment. <a href="https://github.com/finxter/flask_email_verifier" data-type="URL" data-id="https://github.com/finxter/flask_email_verifier" target="_blank" rel="noreferrer noopener">Check my GitHub</a> page for the full code.</p>



<p>In your project folder, create a <code>.env</code> file to store your API key. Inside the file write these:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">secret_key = 'Your API Key'</pre>



<p>We then use the <code>config</code> class to load the API key. This is a safe way to import sensitive information. After sending a <a href="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" data-type="post" data-id="37837" target="_blank" rel="noreferrer noopener">GET request</a> to the API, we have the following as the response converted to JSON if the email is valid:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
   "email":"support@emailvalidation.io",
   "user":"support",
   "tag":"",
   "domain":"emailvalidation.io",
   "smtp_check":true,
   "mx_found":true,
   "did_you_mean":"",
   "role":true,
   "disposable":false,
   "score":0.95,
   "state":"deliverable",
   "reason":"valid_mailbox",
   "free":false,
   "format_valid":true,
   "catch_all":"None"
}
</pre>



<p>The main fields to watch out for that confirms the authenticity of an email address are, <code>format_valid</code>, <code>mx_found</code>, <code>smtp_check</code>, and <code>state</code>. You can learn about them <a href="https://emailvalidation.io/docs/info#sample-response" data-type="URL" data-id="https://emailvalidation.io/docs/info#sample-response">here</a>.</p>



<p>The <code>is_valid_function()</code> function returns <code>True</code> if all the four fields are <code>True</code> else, it returns <code>False</code>. We will then call this function in our Flask application. </p>



<p>Create an <code>app.py</code> file and write the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from flask import Flask, render_template, request
from email_verifier import is_valid_email


app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def index():
    # checking if the method is POST
    if request.method == 'POST':
        # getting the email from the form input
        email = request.form['email-address']
        if is_valid_email(email) == True:
            response = f'Your email, {email} is valid'
            return render_template('index.html', response=response)
        else:
            response = f'Your email, {email} is not valid'
            return render_template('index.html', response=response)
    return render_template('index.html')
</pre>



<p>You can see we import the <code>is_valid_email()</code> function as well as the <code>Flask</code> class and other important functions we will use. After creating the application object and the routes, we send a POST request to retrieve data from the <code>index.html</code> file. This is the email address the user will input.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="713" height="401" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-124.png" alt="" class="wp-image-1354891" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-124.png 713w, https://blog.finxter.com/wp-content/uploads/2023/05/image-124-300x169.png 300w" sizes="auto, (max-width: 713px) 100vw, 713px" /></figure>
</div>


<p>We then send it to the <code>is_valid_email()</code> function. </p>



<p>If it returns <code>True</code>, we use the <code>render_template</code> function to display a message stored in the <code>response</code> variable to the <code>index.html</code> file. In the <code>render_template()</code>, the <code>response</code> attribute is from the <code>index.html</code> file, the other <code>response</code> (a variable) is the one with the message.</p>



<p>If the callback function returns <code>False</code>, we display a different message. If the request is not POST, we simply display the empty form on the webpage.</p>



<h2 class="wp-block-heading">Conclusion</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="920" height="613" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-127.png" alt="" class="wp-image-1354896" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-127.png 920w, https://blog.finxter.com/wp-content/uploads/2023/05/image-127-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/05/image-127-768x512.png 768w" sizes="auto, (max-width: 920px) 100vw, 920px" /></figure>
</div>


<p>We have learned how to implement an email verifier feature in a Flask application. There are so many ways to create this app as well as other <a href="https://www.abstractapi.com/email-verification-validation-api" data-type="URL" data-id="https://www.abstractapi.com/email-verification-validation-api" target="_blank" rel="noreferrer noopener">APIs</a> you can use to verify email addresses. You can implement this feature while creating user authentication in your Flask application. </p>



<p>By working on projects such as this, you are improving your skills and gaining confidence as a web developer.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/full-stack-web-developer-income-and-opportunity/" data-type="URL" data-id="https://blog.finxter.com/full-stack-web-developer-income-and-opportunity/" target="_blank" rel="noreferrer noopener">Full-Stack Web Developer — Income and Opportunity</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-an-email-address-verifier-using-flask/">How I Created an Email Address Verifier Using Flask</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I created a News Application using the Flask Framework</title>
		<link>https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/</link>
		
		<dc:creator><![CDATA[Jonathan Okah]]></dc:creator>
		<pubDate>Mon, 01 May 2023 07:08:21 +0000</pubDate>
				<category><![CDATA[Flask]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1330088</guid>

					<description><![CDATA[<p>As part of your journey to becoming a web developer, working on projects is a compulsory requirement. You gain experience, exposure, and the necessary skills to increase your chances of getting a job. 💡 In this tutorial, we will use Flask, one of Python&#8217;s web development framework to create a News application. We will make ... <a title="How I created a News Application using the Flask Framework" class="read-more" href="https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/" aria-label="Read more about How I created a News Application using the Flask Framework">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/">How I created a News Application using the Flask Framework</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>As part of your journey to becoming a <a rel="noreferrer noopener" href="https://blog.finxter.com/full-stack-web-developer-income-and-opportunity/" data-type="post" data-id="326336" target="_blank">web developer</a>, working on projects is a compulsory requirement. You gain experience, exposure, and the necessary skills to increase your chances of getting a job.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> In this tutorial, we will use <a rel="noreferrer noopener" href="https://blog.finxter.com/how-i-deployed-a-machine-learning-application-using-the-flask-webserver/" data-type="post" data-id="1291985" target="_blank">Flask</a>, one of Python&#8217;s web development framework to <strong>create a News application</strong>. We will make use of an API to fetch the latest news.</p>



<p>Our <a rel="noreferrer noopener" href="https://blog.finxter.com/how-i-built-a-weather-app-using-python-flask/" data-type="post" data-id="1271319" target="_blank">previous Flask project tutorial</a> that involved using an API was when we created a weather app, it was there we introduced Flask. Feel free to check it out to become more familiar with Flask!</p>



<h2 class="wp-block-heading">Getting started</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="594" height="892" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-2.png" alt="" class="wp-image-1330100" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-2.png 594w, https://blog.finxter.com/wp-content/uploads/2023/05/image-2-200x300.png 200w" sizes="auto, (max-width: 594px) 100vw, 594px" /></figure>
</div>


<p>Create a folder for this project. Inside the folder, create and activate a virtual environment. </p>



<p>Afterward, <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-flask-in-python/" data-type="post" data-id="35862" target="_blank">install Flask</a>, <code>python-dotenv</code>, <code>python-decouple</code> and the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library/" data-type="post" data-id="37796" target="_blank">requests</a></code> module. </p>



<p>Finally, create a <code>requirements.txt</code> file to store the module versions which will be used in case a future version affects the smooth running of this application.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir &amp;&amp; cd project
pip -m venv .venv
source .venv/bin/activate
pip install flask python-dotenv python-decouple requests
pip freeze > requirements.txt</pre>



<p>We use both <code>python-dotenv</code> and <code>python-decouple</code> to load environment variables. Requests will be used to fetch the latest news headlines.</p>



<h2 class="wp-block-heading">News API</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="861" height="574" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-3.png" alt="" class="wp-image-1330101" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-3.png 861w, https://blog.finxter.com/wp-content/uploads/2023/05/image-3-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/05/image-3-768x512.png 768w" sizes="auto, (max-width: 861px) 100vw, 861px" /></figure>
</div>


<p>For this project, we will use <a href="https://newsapi.org/" target="_blank" rel="noreferrer noopener">News API2</a> to fetch the latest news. Sign up for a free account to receive your API key. Then create a <code>.env</code> file in the project directory, and store your API key there.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">NEWS_API_KEY = 'YOUR_API_KEY'</pre>



<p>Then, create a <code>main.py</code> file and add the following script to it:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from flask import Flask, render_template
import requests
from decouple import config


API_KEY = config('NEWS_API_KEY')

app = Flask(__name__)

country = 'us'

@app.route('/')
def news_headlines():
    url = f'https://newsapi.org/v2/top-headlines?country={country}&amp;apiKey={API_KEY}'
    res = requests.get(url).json()
    news_articles = res['articles']
    return render_template('index.html', news_articles=news_articles)
</pre>



<p>As usual, we import the Flask app and creates the application object as an instance of the class. The <code>__name__</code> variable passed to the Flask class is used, among other things, to locate associated resources such as templates.</p>



<p>We follow best practices regarding storing sensitive information such as API key. Instead of exposing our API key, we store it in a <code>.env</code> file. Then use the <code>config</code> class from the <code>python-decouple</code> module to get the values of the environment variable.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-designed-a-news-aggregator-web-application-using-django/" data-type="URL" data-id="https://blog.finxter.com/how-i-designed-a-news-aggregator-web-application-using-django/" target="_blank" rel="noreferrer noopener">How I Designed a News Aggregator Web Application Using Django</a></p>



<p>We also set the country to United States to get the latest news happening in the country. Of course, you can use any country of your choice. Check the <a href="https://newsapi.org/docs/endpoints/top-headlines" data-type="URL" target="_blank" rel="noreferrer noopener">documentation</a> to know the country code.</p>



<p>The <code>news_headlines()</code> function has a <code>@app.route</code> <a href="https://blog.finxter.com/an-introduction-to-closures-and-decorators-in-python/" data-type="post" data-id="33290" target="_blank" rel="noreferrer noopener">decorator</a> that links the function to the associated URL. The return value of the function will be displayed to the browser when the URL is requested.</p>



<p>Using the <code>requests</code> module, we make a GET request to the URL of the News API. The response is converted into JSON. We save the <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a> containing the news in a variable, and pass it to the <code>render_template()</code> function.</p>



<h2 class="wp-block-heading">Templates</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="861" height="574" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-4.png" alt="" class="wp-image-1330103" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-4.png 861w, https://blog.finxter.com/wp-content/uploads/2023/05/image-4-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/05/image-4-768x512.png 768w" sizes="auto, (max-width: 861px) 100vw, 861px" /></figure>
</div>


<p>Flask, by default, searches for template files in the <code>template</code> folder. So, we have to create the folder, and also create an <code>index.html</code> file. Remember, this was passed to the <code>render_template()</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html lang="en">
  &lt;head>
    &lt;!-- Required meta tags -->
    &lt;meta charset="utf-8" />
    &lt;meta name="viewport" content="width=device-width, initial-scale=1" />
    &lt;!-- Bootstrap CSS -->
    &lt;link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    &lt;title>Flask Latest News&lt;/title>
  &lt;/head>
  &lt;body>
    &lt;h1 class="text-center mt-4 mb-5">Flask Latest News Headlines&lt;/h1>
    &lt;div class="row mt-5">
      &lt;div class="col-md-2">&lt;/div>
      &lt;div class="col-md-8">
        &lt;div class="row">
          {% for news in news_articles %}
          &lt;div class="col-md-4 mb-5">
            &lt;div class="card" style="width: 18rem">
              &lt;img src="{{ news.urlToImage }}" class="card-img-top" alt="..." />
              &lt;div class="card-body">
                &lt;h5 class="card-title">{{ news.title }}&lt;/h5>
                &lt;p class="card-text">{{ news.description }}&lt;/p>
                &lt;a href="{{ news.url }}" class="btn btn-primary">Read More&lt;/a>
              &lt;/div>
            &lt;/div>
          &lt;/div>
          {% endfor %}
        &lt;/div>
      &lt;/div>
      &lt;div class="col-md-2">&lt;/div>
    &lt;/div>
    &lt;!-- Bootstrap Bundle with Popper -->
    &lt;script
   src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    >&lt;/script>
  &lt;/body>
&lt;/html>
</pre>



<p>We use <a href="https://blog.finxter.com/bootstrap-developer-income-and-opportunity/" data-type="post" data-id="217919" target="_blank" rel="noreferrer noopener">Bootstrap</a> to style the website. Each news headline gotten from the News API has an image, a title, description, and a link to read more. So, we use Jinja2 <code>for</code>-loop to iterate over the <code>news_articles</code>. </p>



<p>The <code>urlToImage</code> is the URL for the image of the article.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="713" height="401" src="https://blog.finxter.com/wp-content/uploads/2023/05/image.png" alt="" class="wp-image-1330096" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image.png 713w, https://blog.finxter.com/wp-content/uploads/2023/05/image-300x169.png 300w" sizes="auto, (max-width: 713px) 100vw, 713px" /></figure>
</div>


<h2 class="wp-block-heading">Conclusion</h2>



<p>This is a how we use an API to fetch the current news headlines and have them rendered on our Flask application. It is a very simple project for beginners. No doubt, you have learned a lot from this project tutorial. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4aa.png" alt="💪" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>In upcoming tutorials, I&#8217;m going to demonstrate how to create this application using the Django framework. To run the Flask app, create a <code>.flaskenv</code> file and write the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">FLASK_APP=main.py</pre>



<p>Now that we have taken care that, we will not always have to set the <code>FLASK_APP</code> environment variable whenever we want to run the flask command. Make sure you have installed the <code>python-dotenv</code> package.</p>



<p>We are done. Just type <code>flask run</code> in your terminal, hit the Enter key to start the local server, and get the latest news. The full code is available on my <a href="https://github.com/finxter/flask_news_app" data-type="URL" data-id="https://github.com/finxter/flask_news_app">GitHub page</a>. Alright, enjoy your day!</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-deployed-a-machine-learning-application-using-the-flask-webserver/" data-type="post" data-id="1291985" target="_blank" rel="noreferrer noopener">How I Deployed a Machine Learning Application Using the Flask Webserver</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-news-application-using-the-flask-framework/">How I created a News Application using the Flask Framework</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Deployed a Machine Learning Application Using the Flask Webserver</title>
		<link>https://blog.finxter.com/how-i-deployed-a-machine-learning-application-using-the-flask-webserver/</link>
		
		<dc:creator><![CDATA[Jonathan Okah]]></dc:creator>
		<pubDate>Fri, 14 Apr 2023 18:42:13 +0000</pubDate>
				<category><![CDATA[Flask]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1291985</guid>

					<description><![CDATA[<p>Deployment of Machine Learning models to make them available to end users is the ultimate goal of data scientists. How can you develop a web application if you have little or no knowledge of web development? As data scientists, you can now see that learning Python for web development cannot be overemphasized. There are many ... <a title="How I Deployed a Machine Learning Application Using the Flask Webserver" class="read-more" href="https://blog.finxter.com/how-i-deployed-a-machine-learning-application-using-the-flask-webserver/" aria-label="Read more about How I Deployed a Machine Learning Application Using the Flask Webserver">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-deployed-a-machine-learning-application-using-the-flask-webserver/">How I Deployed a Machine Learning Application Using the Flask Webserver</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Deployment of Machine Learning models to make them available to end users is the ultimate goal of data scientists. How can you develop a web application if you have little or no knowledge of web development? As data scientists, you can now see that learning Python for web development cannot be overemphasized.</p>



<p>There are many Python frameworks used in building Machine Learning web applications. A <a href="https://blog.finxter.com/how-i-created-a-machine-learning-web-application-using-django/" data-type="post" data-id="1242421" target="_blank" rel="noreferrer noopener">project tutorial</a> showing how to build a Machine Learning web app using the Django web framework has been demonstrated. </p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f4bb.png" alt="👩‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-created-a-machine-learning-web-application-using-django/" data-type="post" data-id="1242421" target="_blank" rel="noreferrer noopener">How I Created a Machine Learning Web Application Using Django</a></p>



<p>In today&#8217;s tutorial, we are going to see how this can be done using the Flask web framework.</p>



<p>Flask is a micro framework written in Python for building interactive web pages. It is called a <strong><em>small framework</em></strong> because it is easy to read and understand once you become familiar with it.</p>



<h2 class="wp-block-heading">Objectives</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="697" height="911" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-136.png" alt="" class="wp-image-1292014" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-136.png 697w, https://blog.finxter.com/wp-content/uploads/2023/04/image-136-230x300.png 230w" sizes="auto, (max-width: 697px) 100vw, 697px" /></figure>
</div>


<p>The objective of this tutorial is to show you the steps I took to deploy a Machine Learning model using Flask. Specifically, you will learn how the Flask framework interacts with our Machine Learning models.</p>



<h2 class="wp-block-heading">The Model</h2>



<p>We start by creating a <code>model.py</code> file in a new directory. Our task is to train a model to classify the gender of an individual based on height, weight and foot size. You can see that this is a classification problem. Hence, we will use Random Forest Classifier algorithm. Download the dataset from <a href="https://github.com/finxter/flask_machine_learning" data-type="URL" data-id="https://github.com/finxter/flask_machine_learning" target="_blank" rel="noreferrer noopener">my GitHub page</a>.</p>



<p>We keep things simple so we can focus on our objectives, that is, to implement Machine Learning using the Flask framework. The dataset has 155 rows and 4 features, including GENDER, the target feature. In the GENDER column, 1 means male and 2 means female.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
from sklearn.ensemble import  RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import joblib

df = pd.read_csv('gender_classifier.csv')
X = df.drop(['GENDER'], axis=1)
y = df.GENDER
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=5)
model = RandomForestClassifier()
model.fit(X_train.values, y_train.values)
preds = model.predict(X_test.values)
accuracy_score(y_test,preds)*100
# 90.32258064516128</pre>



<p>We achieved an accuracy score of 90% with this simple way we trained the model. The final thing to do in this file is to pickle the trained model for further use.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">joblib.dump(model, 'rf_model.pkl')</pre>



<p>If you have been following all along, I expect your folder to have the following files:<br></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">gender_classifier.csv model.py rf_model.pkl</pre>



<h2 class="wp-block-heading">Creating a Flask App</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="682" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-135-1024x682.png" alt="" class="wp-image-1292013" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-135-1024x682.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-135-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-135-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-135.png 1168w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>If you are new to the Flask framework, <a href="https://www.section.io/engineering-education/complete-guide-on-installing-flask-for-beginners/" data-type="URL" data-id="https://www.section.io/engineering-education/complete-guide-on-installing-flask-for-beginners/" target="_blank" rel="noreferrer noopener">this</a> article can set you up for the remaining part of this tutorial. The first step in creating a flask app is to define the application object as an instance of the <code>Flask</code> class. Create a file named <code>flask_app.py</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from flask import Flask, request, render_template
import joblib
import pandas as pd

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        model = joblib.load('rf_model.pkl')

        height = request.form['heit']
        hand_len = request.form['hlen']
        foot_len = request.form['flen']

        mapping = {1: 'Male', 2: 'Female'}

        df = pd.DataFrame([[height, hand_len, foot_len]], columns=['height', 'hand_len', 'foot_len'])
        prediction = model.predict(df.values)[0]
        results = mapping[prediction]

        return render_template('index.html', results=results)
    return render_template('index.html')


if __name__ == '__main__':
    app.run(debug=True)
</pre>



<p>The <strong><code>__name__</code></strong> variable is Python predefined variable used by Flask to find the location of all the resources necessary for the smooth running of the app.</p>



<p>We create a function known as the view function that handles the application routes. Routes are simply the URLs implemented by the application. The <code>index()</code> function is mapped to the route URL represented as <code>/</code> which means the home page. When a client requests a URL such as the above, Flask executes the view function.</p>



<p>The view function has a <a href="https://blog.finxter.com/an-introduction-to-closures-and-decorators-in-python/" data-type="post" data-id="33290" target="_blank" rel="noreferrer noopener">Python decorator</a> <code>@app.route</code>. This links the function to the URL passed as an argument. Thus, when a client requests a given URL, Flask will not only execute the function, it will also pass the function’s return value back to the browser as a response.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f4bb.png" alt="👩‍💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/an-introduction-to-closures-and-decorators-in-python/" data-type="post" data-id="33290" target="_blank" rel="noreferrer noopener">An Introduction To Closures and Decorators in Python</a></p>



<p>The route has two methods, GET and POST. They are used to retrieve data from template files. In the template file, we will create a form where users will input their height, hand length and foot length. Are you starting to see the connection? Once the data are retrieved, the trained model is <a href="https://blog.finxter.com/python-pickle-module-simplify-object-persistence-ultimate-guide/" data-type="post" data-id="1289330" target="_blank" rel="noreferrer noopener">unpickled</a> and used to make prediction based on the data.</p>



<p>All these will execute provided the request method is POST. The request method is used to send data to the server. Check out <a href="https://pythonbasics.org/flask-http-methods/" data-type="URL" data-id="https://pythonbasics.org/flask-http-methods/" target="_blank" rel="noreferrer noopener">this</a> article to learn more about them. How will Flask know if the request method is POST? We will find the answer when we create the template file.</p>



<p>Finally, we render the returned value using the <code>render_template()</code> method, which has the HTML file that will be displayed to the user. Notice the arguments passed to <code>render_template()</code> method. The results of the predictions! </p>



<p>Can you see how the Flask framework interacts with our Machine Learning model? Then, to run the Flask webserver, we use the <code>app.run()</code> method.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="708" height="398" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-132.png" alt="" class="wp-image-1292002" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-132.png 708w, https://blog.finxter.com/wp-content/uploads/2023/04/image-132-300x169.png 300w" sizes="auto, (max-width: 708px) 100vw, 708px" /></figure>



<h2 class="wp-block-heading">The Template File</h2>



<p>Create a folder named <code>templates</code>. By now, your main folder should have the following files:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">__pycache__  flask_app.py  gender_classifier.csv  model.py  rf_model.pkl  templates </pre>



<h2 class="wp-block-heading">Gender Classification</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="683" height="911" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-134.png" alt="" class="wp-image-1292012" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-134.png 683w, https://blog.finxter.com/wp-content/uploads/2023/04/image-134-225x300.png 225w" sizes="auto, (max-width: 683px) 100vw, 683px" /></figure>
</div>


<p>A Machine Learning model to determine the gender of an individual</p>



<p>Inside the template folder, create an <code>index.html</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;DOCTYPE html>
&lt;html>
  &lt;head>
   &lt;title>Gender Classification&lt;/title>
   &lt;body style="background:black; color:white; text-align:center">
     &lt;h1 style="color:blue">Gender Classification&lt;/h1>
      &lt;h3>A Machine Learning model to determine the gender of an individual&lt;/h3>
      &lt;div>
        &lt;form action="{{ url_for('index') }}" method="POST">
            &lt;div style="width: 400px">
                &lt;div>
                    &lt;p>
                    Height: &lt;input type="number" value='0.00' step="0.01" name="heit" id="heit">
                    &lt;/p>
                &lt;/div>

                &lt;div>
                    &lt;p>
                    Hand Length: &lt;input type="number" value='0.00' step="0.01" name="hlen" id="hlen">
                    &lt;/p>
                &lt;/div>

                &lt;div>
                    &lt;p>
                    Foot Length: &lt;input type="number" value='0.00' step="0.01" name="flen" id="flen">
                    &lt;/p>
                &lt;/div>
                &lt;div>
                    &lt;button>Submit&lt;/button>
                &lt;/div>
                {% if results %}
                &lt;p>The individual is a {{ results }}&lt;/p>
                {% endif %}
                &lt;/div>
            &lt;/div>
        &lt;/form>
    &lt;/div>
  &lt;/body>
</pre>



<p>The form element has the request method as <code>POST</code>. The action argument points to the <code>index()</code> view function. Once the submit button is pressed, the data collected through the form will be sent to the <code>index()</code> function. Then, the result will be generated and displayed.</p>



<h2 class="wp-block-heading">Conclusion</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="682" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-133-1024x682.png" alt="" class="wp-image-1292009" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-133-1024x682.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/04/image-133-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-133-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2023/04/image-133.png 1168w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>We have created a Machine Learning web application using the Flask framework. <a rel="noreferrer noopener" href="https://github.com/finxter/flask_machine_learning" data-type="URL" data-id="https://github.com/finxter/flask_machine_learning" target="_blank">Check out my GitHub page</a> for the complete code. Keep practicing project tutorials like this. In no distant time, you will master the Flask framework.</p>
<p>The post <a href="https://blog.finxter.com/how-i-deployed-a-machine-learning-application-using-the-flask-webserver/">How I Deployed a Machine Learning Application Using the Flask Webserver</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Used the Flask Framework to Create an URL Shortener Application</title>
		<link>https://blog.finxter.com/how-i-used-the-flask-framework-to-create-an-url-shortener-application/</link>
		
		<dc:creator><![CDATA[Jonathan Okah]]></dc:creator>
		<pubDate>Thu, 13 Apr 2023 16:52:48 +0000</pubDate>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1289207</guid>

					<description><![CDATA[<p>A URL shortener service generates a shorter, more readable version of the URL it was given. Flask, a Python web framework can be used to create a URL shortener app. So, we will create an application allowing users to enter a URL and shorten it. We will use the SQLite database engine to store application ... <a title="How I Used the Flask Framework to Create an URL Shortener Application" class="read-more" href="https://blog.finxter.com/how-i-used-the-flask-framework-to-create-an-url-shortener-application/" aria-label="Read more about How I Used the Flask Framework to Create an URL Shortener Application">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-used-the-flask-framework-to-create-an-url-shortener-application/">How I Used the Flask Framework to Create an URL Shortener Application</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A URL shortener service generates a shorter, more readable version of the URL it was given. Flask, a Python web framework can be used to create a URL shortener app. </p>



<p>So, we will create an application allowing users to enter a URL and shorten it. We will use the SQLite database engine to store application data.<br>If you prefer to learn how this is done using the <a href="https://blog.finxter.com/how-i-created-an-url-shortener-app-using-django/" data-type="post" data-id="1196939" target="_blank" rel="noreferrer noopener">Django framework, you are free to read this article</a>.</p>



<h2 class="wp-block-heading">Set up</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="773" height="579" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-109.png" alt="" class="wp-image-1289261" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-109.png 773w, https://blog.finxter.com/wp-content/uploads/2023/04/image-109-300x225.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-109-768x575.png 768w" sizes="auto, (max-width: 773px) 100vw, 773px" /></figure>
</div>


<p>Create a new folder for this project. Then, create and <a href="https://blog.finxter.com/setup-a-virtual-environment-with-visual-studio-code-in-python/" data-type="post" data-id="935562" target="_blank" rel="noreferrer noopener">activate a virtual environment</a> by running the following commands in your terminal.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">python3 -m venv venv
source venv/bin/activate</pre>



<p><a href="https://blog.finxter.com/how-to-install-flask-in-python/" data-type="post" data-id="35862" target="_blank" rel="noreferrer noopener">Install Flask</a> and the <code>hashids</code> library.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install flask hashids</pre>



<p>The <code>hashids</code> library will be used to generate a unique ID. You will understand this as we proceed.</p>



<h2 class="wp-block-heading">Creating a Database Engine</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="773" height="515" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-110.png" alt="" class="wp-image-1289263" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-110.png 773w, https://blog.finxter.com/wp-content/uploads/2023/04/image-110-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-110-768x512.png 768w" sizes="auto, (max-width: 773px) 100vw, 773px" /></figure>
</div>


<p>Since we will store application data, we must create a database file. Do it and call the file <code>schema.sql</code>. Then, write the following SQL commands.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">DROP TABLE IF EXISTS urls;
CREATE TABLE urls(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  original_url TEXT NOT NULL,
  clicks INTEGER NOT NULL DEFAULT 0
);</pre>



<p>If the above code seems strange, you may want to familiarize yourself with SQL commands. </p>



<p>We want to create a table named <code>urls</code>. As we don’t want to face issues caused by several tables with the same name, we must first delete it. That’s what is meant by ‘<code>DROP TABLE…</code>’</p>



<p>The table is then created with four columns. The <code>id</code> column will contain the unique integer value for each entry. Next is the date the shortened URL was generated. The third column is the original URL. Finally, the number of times the URL was clicked.</p>



<p>The <code>schema.sql</code> file can only be executed with the help of a Python script. So, we create another file called <code>init_db.py</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import Sqlite3

connection = Sqlite3.connect('database.db')

with open('schema.sql') as sql:
    connection.executescript(sql.read())

connection.commit()
connection.close()
</pre>



<p></p>



<p>Once you run the script (with <code>python3 init_db.py</code>), a new file called <code>database.db</code> will be created. This is where all application data will be stored.</p>



<p>The <code>connect()</code> method creates the file. As soon as the file is created, it is then populated with the urls table. This is done by first opening and reading the content from the <code>schema.sql</code>. </p>



<p>It then calls the <code>executescript()</code> method to execute all the SQL commands in the SQL file. After which, we commit and close the file. By now, your folder should contain the following files:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">database.db init_db.py schema.sql</pre>



<h2 class="wp-block-heading">Creating the Database Connection</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="607" height="911" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-111.png" alt="" class="wp-image-1289264" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-111.png 607w, https://blog.finxter.com/wp-content/uploads/2023/04/image-111-200x300.png 200w" sizes="auto, (max-width: 607px) 100vw, 607px" /></figure>
</div>


<p>Let us open a connection to the database file. Create a file and name it <code>db_connection.py</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import sqlite3

def get_db_connection():
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn
</pre>



<p>Notice that we set the row-factory attribute to <code>sqlite3.Row</code>. This makes it possible to access values by column name. We then return the connection object, which will be used to access the database.</p>



<h2 class="wp-block-heading">The Main File</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="607" height="911" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-112.png" alt="" class="wp-image-1289267" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-112.png 607w, https://blog.finxter.com/wp-content/uploads/2023/04/image-112-200x300.png 200w" sizes="auto, (max-width: 607px) 100vw, 607px" /></figure>
</div>


<p>Next, create another file and name it <code>main.py</code>. This will be our main file. In this file, we will import the database connection file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from db_connection import get_db_connection
from hashids import Hashids
from flask import Flask, flash, render_template, request, url_for, redirect

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Your secret key'

hashids = Hashids(min_length=4, salt=app.config['SECRET_KEY'])

@app.route('/', methods=('GET', 'POST'))
def index():
    conn = get_db_connection()
    if request.method == 'POST':
        url = request.form['url']

        if not url:
            flash('The URL is required!')
            return redirect(url_for('index'))

        url_data = conn.execute('INSERT INTO urls (original_url) VALUES (?)', (url,))
        conn.commit()
        conn.close()

        url_id = url_data.lastrowid
        hashid = hashids.encode(url_id)
        short_url = request.host_url + hashid
        return render_template('index.html', short_run=short_url)
    return render_template('index.html')
</pre>



<p>We create an instance of the Flask class. The <code>__name__</code> variable allows Flask to locate other resources, including templates in the current directory. We then create hashids object that will have four characters. (You can choose to have more characters). We use a secret key to specify the salt for the Hashids library. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-107.png" alt="" class="wp-image-1289239" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-107.png 720w, https://blog.finxter.com/wp-content/uploads/2023/04/image-107-300x169.png 300w" sizes="auto, (max-width: 720px) 100vw, 720px" /></figure>
</div>


<p>The <code>index()</code> function is decorated with the <code>@app.route</code> <a href="https://blog.finxter.com/3-top-design-patterns-in-python-singletons-decorators-and-iterators/" data-type="post" data-id="151218" target="_blank" rel="noreferrer noopener">decorator</a> that assigns the URL (<code>'/'</code>) to the function, thus turning it into a Flask view function.</p>



<p>In the <code>index()</code> function, we open a database connection. Then, we check if the request method is POST. If so, the code block under it will be executed. If not, we only return an empty web page using the <code>render_template()</code> method.</p>



<p>If the request method is POST, we use <code>request.form['url']</code> to collect input from the template file (<code>index.html</code>). The output is the URL to shorten. However, if the user gives no URL, we simply flash a message and redirect the user back to the same <code>index.html</code> web page.</p>



<p>If a URL is given, it will be added to the database by executing the command, <code>INSERT INTO …</code></p>



<p>After closing the database, we select the last row id of the database, which is the current URL added. Remember the AUTOINCREMENT keyword in the id column of the database file. This ensures that the id is incremented with each new entry.</p>



<p>With the last row id selected, we use the <code>hashids.encode()</code> method to generate a unique hash and concatenate it to the URL of the application’s host (indicated with the <code>request.host_url</code> attribute). This becomes the shortened URL that would be displayed to the user.</p>



<p>Please <a href="https://github.com/finxter/flask_url_shortener" data-type="URL" data-id="https://github.com/finxter/flask_url_shortener" target="_blank" rel="noreferrer noopener">check my GitHub page</a> for the template files. Make sure you create a templates folder to keep the HTML files.</p>



<p>The local server is opened when you run <code>python3 main.py</code> in your terminal. This is possible because of the special <code>name</code> variable and the <code>app.run()</code> method.</p>



<h2 class="wp-block-heading">Adding Extra Features</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="607" height="911" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-113.png" alt="" class="wp-image-1289268" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-113.png 607w, https://blog.finxter.com/wp-content/uploads/2023/04/image-113-200x300.png 200w" sizes="auto, (max-width: 607px) 100vw, 607px" /></figure>
</div>


<p>Won’t it be nice to know how many times each URL has been clicked and have them displayed on a web page? We are going to add that feature. Update your <code>app.py</code> by adding the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@app.route('/stats')
def stats():
    conn = get_db_connection()
    db_urls = conn.execute('SELECT * FROM urls').fetchall()
    conn.close()

    urls = []
    for url in db_urls:
        url = dict(url)
        url['short_url'] = request.host_url + hasids.encode(url['id'])
        urls.append(url)
    return render_template('stats.html', urls=urls)</pre>



<p>We again open a database connection, and fetch all the columns in the urls table (indicated by <code>*</code>) and a <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a> of all the rows using the <code>fetchall()</code> method.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-108.png" alt="" class="wp-image-1289254" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-108.png 720w, https://blog.finxter.com/wp-content/uploads/2023/04/image-108-300x169.png 300w" sizes="auto, (max-width: 720px) 100vw, 720px" /></figure>



<p>After closing the database, we loop through the result. In each iteration, we convert the <code>sqlite3.Row</code> object to a <a href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank" rel="noreferrer noopener">dictionary</a> and repeat the same thing we did previously to encode the id number. This is then concatenated to form a new URL. Finally, we <a href="https://blog.finxter.com/python-list-append/" data-type="post" data-id="6605" target="_blank" rel="noreferrer noopener">append the result</a> to an empty list and render it to the browser. </p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Notice we didn’t commit the database as we did previously. This is because we didn’t make changes to the database. We close it after fetching the data we needed.</p>



<p>Your folder should now have the following files:</p>



<ul class="wp-block-list">
<li><code>database.db</code>, </li>



<li><code>db_connection.py</code>, </li>



<li><code>init_db.py</code>, </li>



<li><code>main.py</code>, </li>



<li><code>schema.sql</code>, <code>templates</code>.</li>
</ul>



<p></p>



<h2 class="wp-block-heading">Templates Files</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="773" height="511" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-114.png" alt="" class="wp-image-1289269" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-114.png 773w, https://blog.finxter.com/wp-content/uploads/2023/04/image-114-300x198.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-114-768x508.png 768w" sizes="auto, (max-width: 773px) 100vw, 773px" /></figure>
</div>


<p>As earlier stated, you should check my <a href="https://github.com/finxter/flask_url_shortener" data-type="URL" data-id="https://github.com/finxter/flask_url_shortener">GitHub page</a> for the templates files. We created a <code>base.html</code> file inside the <code>templates</code> folder that other files will inherit. </p>



<p>The other two files have certain things that make rendering dynamic content to our Flask web page possible. It is the <code>{% ... %}</code> and <code>{ ... }</code> code blocks. </p>



<p>These are Jinja2 templating language that comes together with the Flask library. </p>



<p>The <code>render_templates()</code> method in the <code>stats()</code> function has another argument, <code>urls</code>. This is from the <code>stats.html</code> web page, while the other <code>urls</code> is the variable that will be displayed on the web page.</p>



<h2 class="wp-block-heading">Conclusion</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="607" height="911" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-115.png" alt="" class="wp-image-1289273" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-115.png 607w, https://blog.finxter.com/wp-content/uploads/2023/04/image-115-200x300.png 200w" sizes="auto, (max-width: 607px) 100vw, 607px" /></figure>
</div>


<p>This is one of the ways to create a URL shortener app using the Flask framework. This project has expose us to how Flask works as well as how it interacts with database. If you struggle to understand some of what we did, that should be expected as a beginner. However, as you keep working on projects, it will become second nature to you.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-created-an-url-shortener-app-using-django/" data-type="post" data-id="1196939" target="_blank" rel="noreferrer noopener">How I Created an URL Shortener App Using Django</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-used-the-flask-framework-to-create-an-url-shortener-application/">How I Used the Flask Framework to Create an URL Shortener Application</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Built a Weather App Using Python Flask</title>
		<link>https://blog.finxter.com/how-i-built-a-weather-app-using-python-flask/</link>
		
		<dc:creator><![CDATA[Jonathan Okah]]></dc:creator>
		<pubDate>Thu, 06 Apr 2023 09:18:43 +0000</pubDate>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1271319</guid>

					<description><![CDATA[<p>In the first part of this series tutorial, we learned how to build a weather app using Django, a powerful Python framework for building web applications. Although not a prerequisite to understanding this second part, learning how to design such an application is worth your time. For the very first time, I will be explaining ... <a title="How I Built a Weather App Using Python Flask" class="read-more" href="https://blog.finxter.com/how-i-built-a-weather-app-using-python-flask/" aria-label="Read more about How I Built a Weather App Using Python Flask">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-built-a-weather-app-using-python-flask/">How I Built a Weather App Using Python Flask</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In the first part of this series tutorial, we learned <a rel="noreferrer noopener" href="https://blog.finxter.com/how-i-built-a-weather-app-using-three-python-frameworks/" data-type="post" data-id="1250320" target="_blank">how to build a weather app</a> using Django, a powerful Python framework for building web applications. Although not a prerequisite to understanding this second part, learning how to design such an application is worth your time.</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="925" height="582" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-55.png" alt="" class="wp-image-1271358" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-55.png 925w, https://blog.finxter.com/wp-content/uploads/2023/04/image-55-300x189.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-55-768x483.png 768w" sizes="auto, (max-width: 925px) 100vw, 925px" /></figure>



<p>For the very first time, I will be explaining how I design an application using the Flask framework. Like Django, Flask is a web application framework written in Python. Unlike, Django, it is easy to get started as a beginner. In just seven lines of code, you will write your first introduction to the framework, the <code>'Hello, World!'</code> code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()
</pre>



<p>This is all that is required. If you save it in a file called <code>app.py</code>; and run <code>python3 app.py</code> in your terminal, you will see the app running on your local server. Can you see how simple it is? If this was Django, it would require more boilerplate code.</p>



<p>So, in this tutorial, we will learn how to build a weather app using the Flask framework. There is no doubt that building projects using Flask will help you learn and master the framework.</p>



<p>As mentioned in the first part of this series, a weather application is used to get real-time weather information based on cities selected. I assume by now you must have received your API key from <strong>OpenWeatherMap</strong>. If not, please do well to register on the platform to receive your API key which we will use in this tutorial.</p>



<h2 class="wp-block-heading">Prerequisites</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="925" height="520" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-54.png" alt="" class="wp-image-1271357" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-54.png 925w, https://blog.finxter.com/wp-content/uploads/2023/04/image-54-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-54-768x432.png 768w" sizes="auto, (max-width: 925px) 100vw, 925px" /></figure>
</div>


<p>Although this project tutorial is for beginners, you will benefit greatly if you have basic knowledge of Flask. An excellent resource I recommend if you want to go from a beginner to an advanced Flask developer is <a rel="noreferrer noopener" href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" data-type="URL" data-id="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" target="_blank">The Flask Mega Tutorial</a> by Miguel Grinberg.</p>



<h2 class="wp-block-heading">Setting up Flask</h2>



<p>We will first create and activate a virtual environment, which is considered best practice, before installing Flask.</p>



<p>Create and <code>cd</code> into a new folder</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir flask_project &amp;&amp; cd flask_project</pre>



<p>Create and activate a <a href="https://blog.finxter.com/python-virtual-environments-with-venv-a-step-by-step-guide/" data-type="post" data-id="3393" target="_blank" rel="noreferrer noopener">virtual environment</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">python3 -m venv venv
source venv/bin/activate</pre>



<p><a href="https://blog.finxter.com/how-to-install-flask-in-python/" data-type="post" data-id="35862" target="_blank" rel="noreferrer noopener">Install Flask</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install flask</pre>



<p>Install the <code>python-dotenv</code> package to register the environment variable</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install python=dotenv</pre>



<p>Create a <code>requirements.txt</code> file to store the dependencies used in this project.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip freeze > requirements.txt</pre>



<h2 class="wp-block-heading">Starting Flask: A Simple Hello World</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="925" height="616" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-53.png" alt="" class="wp-image-1271356" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-53.png 925w, https://blog.finxter.com/wp-content/uploads/2023/04/image-53-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-53-768x511.png 768w" sizes="auto, (max-width: 925px) 100vw, 925px" /></figure>
</div>


<p>Consider the 7 lines of code mentioned above. We import the Flask class from the <code>flask</code> package. The app variable creates the application object as an instance of the <code>Flask</code> class. The <code>__name__</code> variable configures Flask; and helps it know when and where to find template files.</p>



<p>The <code>hello_world()</code> function has a Python decorator <code>@app.route</code>. Remember, a Python decorator modifies a function. Thus, it is used to register and link the URL (<em><code>/</code>)</em> to the function so that when the URL is requested by a web browser, Flask can easily invoke the function and pass the return value to the browser. Therefore, we can rightly say that a route is the different URLs implemented by the Flask application.</p>



<p>Speaking of templates, they are HTML files written separately and stored in a templates folder. So, instead of directly writing the <code>'Hello, World!'</code> in the function, we can write it in a template file and renders it to the browser.</p>



<p>To demonstrate what I’m talking about, create a <code>template</code> folder. Inside the folder, create an HTML file with the name <code>index.html</code>, and write the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;div>
   &lt;p>Hello, World!&lt;/p>
&lt;/div>
</pre>



<p>Then update the <code>app.py</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html')

if __name__ == '__main__':
    app.run()
</pre>



<p>Run <code>python3 app.py</code> to see the <code>"Hello, World!"</code> now rendered from a template file. This was made possible by the <code>render_template()</code> function. This is the process we will follow to create the weather app.</p>



<h2 class="wp-block-heading">Creating a Form</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="925" height="449" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-52.png" alt="" class="wp-image-1271355" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-52.png 925w, https://blog.finxter.com/wp-content/uploads/2023/04/image-52-300x146.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-52-768x373.png 768w" sizes="auto, (max-width: 925px) 100vw, 925px" /></figure>
</div>


<p>To start building the weather app, we have to create a form. Update the <code>index.html</code> file with the following HTML code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;html lang="en">
  &lt;head>
    &lt;title>Weather App&lt;/title>
  &lt;/head>
  &lt;body>
    &lt;h1>Weather App!&lt;/h1>
    &lt;form method="POST" action="{{ url_for('get_weather')}}">
      &lt;input name="city" type="text" value="{{ request.form['city'] }}">
      &lt;button type="submit">Search&lt;/button>
    &lt;/form>
    {% if data %}
      &lt;p>You have entered: {{ city }}. Country: {{ data['sys']['country'] }}&lt;/p>
      &lt;p>Temperature: {{ data['main']['temp'] }}°C&lt;/p>
      &lt;p>Temperature feeling: {{ data['main']['feels_like']°C }}&lt;/p>
      &lt;p>Pressure: {{ data['main']['pressure'] }}hPa&lt;/p>
      &lt;p>Humidity: {{ data['main']['humidity'] }}&lt;/p>
      {% for i in data['weather'] %}
       &lt;p>Description: {{ i['description'] }}&lt;/p>
      {% endfor %}
    {% endif %}
  &lt;/body>
&lt;/html>
</pre>



<p>A lot of things are going on here. We use the form element to create a form with the method equal to POST. When the submit button is clicked, a request is made with the POST method which makes it possible to collect input values to be accessed in our Python file.</p>



<p>Using the <code>{{ request.form['city'] }}</code> syntax, Flask can easily pick this value in our Python code for further use.</p>



<p>However, all these won’t work without the action property in the form element, that is the <code>get_weather()</code> function.</p>



<h2 class="wp-block-heading">Getting Weather Data</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="925" height="630" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-51.png" alt="" class="wp-image-1271354" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-51.png 925w, https://blog.finxter.com/wp-content/uploads/2023/04/image-51-300x204.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-51-768x523.png 768w" sizes="auto, (max-width: 925px) 100vw, 925px" /></figure>
</div>


<p>Update your <code>app.py</code> with the following code to create the <code>get_weather()</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from flask import Flask, render_template, request
import requests
from openweather import KEY

@app.route('/city', methods=('GET', 'POST'))
def get_weather():
    if request.method == 'POST':
        city = request.form['city']
        url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&amp;units=metric&amp;appid={KEY}'
        res = request.get(url)
        data = res.json()
        return render_template('index.html', city=city, data=data)
    return render_template('index.html')
</pre>



<p>The function is <a href="https://blog.finxter.com/3-top-design-patterns-in-python-singletons-decorators-and-iterators/" data-type="post" data-id="151218" target="_blank" rel="noreferrer noopener">decorated</a> with <code>@app.route</code> which I have already explained. We set the route to be <code>'/city'</code>. If the request method is POST, the input value will be read and saved to the <code>city</code> variable. Next, we use the <code><a href="https://blog.finxter.com/python-requests-library/" data-type="post" data-id="37796" target="_blank" rel="noreferrer noopener">requests</a></code> module to request the URL; and save the response to the <code>res</code> variable. Then we convert the response to a <a href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank" rel="noreferrer noopener">Python dictionary</a> object using <code><a href="https://blog.finxter.com/how-to-return-a-json-object-from-a-function-in-python/" data-type="post" data-id="985215" target="_blank" rel="noreferrer noopener">res.json()</a></code>; and save it to the <code>data</code> variable.</p>



<p>Finally, we display the result to our template using the <code>render_template()</code> function. Notice we passed the <code>city</code> and <code>data</code> variables as arguments to <code>render_template</code>.</p>



<p>If the <code>request</code> method is otherwise, we simply display the template containing the empty form. Before I explain other things here, let’s go back to our <code>index.html</code> file.</p>



<p>The <code>{{ … }}</code> placeholder is used to display dynamic content to the template file. Flask as we know, depends on the Jinja2 template engine. When <code>render_template</code> is called, it equally calls the Jinja2 template engine which substitutes the <code>{{ … }}</code> block with the values provided in the <code>render_template()</code> function.</p>



<p>Jinja2 also supports <a href="https://blog.finxter.com/learn-the-basics-of-micropython-part-2/" data-type="post" data-id="867926" target="_blank" rel="noreferrer noopener">conditional statements</a> and <code>for</code><strong>&#8211;</strong>loops given inside the {% … %} blocks. In that template file, we say, if the data variable is given, display the contents in the p element. Then, we close the conditional statement and the <code>for</code> loop structure.</p>



<p>The conditional statement is important, without which you will get the following error:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Jinja2.exceptions.UndefinedError:
data is undefined
</pre>



<p>This error arises when we try to access a key from a non-existing object. So, do not forget the conditional statement.</p>



<h2 class="wp-block-heading">The API Key</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="925" height="616" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-50.png" alt="" class="wp-image-1271352" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-50.png 925w, https://blog.finxter.com/wp-content/uploads/2023/04/image-50-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-50-768x511.png 768w" sizes="auto, (max-width: 925px) 100vw, 925px" /></figure>
</div>


<p>As mentioned earlier, to make an API call to OpenWeatherMap, you need an API key. Having gotten your API key, you have to keep it safe. Notice how we did in the <code>app.py</code> file. First of all, you create a file called <code>openweather.py</code>. Inside the file, make it look like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">KEY = 'Your API Key'</pre>



<p>Replace the text in quotes with your API key. Can you then see how we imported it to the <code>app.py</code> without exposing the key? If you are deploying this app, you may have to create a <code>.gitignore</code> folder where all sensitive data will be kept to avoid exposing them.</p>



<p>Finally, create a file and name it <code>.flaskenv</code>. In this file, we will register the <code>FLASK_APP</code>  environment variable so that we will not always have to set the environment variable when we run the <code>flask</code> command. Inside the file, write the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">FLASK_APP=app.py</pre>



<p>That’s all. We are done. Now run the flask command like this to test the app:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">flask run</pre>



<p>If you go to <a href="http://127.0.0.1:5000/city">http://127.0.0.1:5000/city</a> in your browser; and type a city of your choice, you will see something similar to the image below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-48.png" alt="" class="wp-image-1271348" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-48.png 720w, https://blog.finxter.com/wp-content/uploads/2023/04/image-48-300x169.png 300w" sizes="auto, (max-width: 720px) 100vw, 720px" /></figure>
</div>


<h2 class="wp-block-heading">Conclusion</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="925" height="520" src="https://blog.finxter.com/wp-content/uploads/2023/04/image-49.png" alt="" class="wp-image-1271351" srcset="https://blog.finxter.com/wp-content/uploads/2023/04/image-49.png 925w, https://blog.finxter.com/wp-content/uploads/2023/04/image-49-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/04/image-49-768x432.png 768w" sizes="auto, (max-width: 925px) 100vw, 925px" /></figure>
</div>


<p>Congratulation on creating a weather app using the Flask framework. You have undoubtedly learned something or two you can add to your knowledge as you continue your web development journey. </p>



<p>You will observe that I added only a little CSS styling so we can focus on the major task. The code is available on <a href="https://github.com/finxter/flask_weather" data-type="URL" data-id="https://github.com/finxter/flask_weather" target="_blank" rel="noreferrer noopener">my GitHub page</a>. In the final part of this series tutorial, we will learn how to create this app using <a href="https://blog.finxter.com/python-streamlit-i-made-this-stock-price-prediction-app/" data-type="post" data-id="1219908" target="_blank" rel="noreferrer noopener">Streamlit</a>.</p>



<p>.</p>
<p>The post <a href="https://blog.finxter.com/how-i-built-a-weather-app-using-python-flask/">How I Built a Weather App Using Python Flask</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>BrainWaves P2P Social Network &#8211; How I Created a Basic Server</title>
		<link>https://blog.finxter.com/brainwaves-p2p-social-network-how-i-created-a-basic-server/</link>
		
		<dc:creator><![CDATA[Tom Teck]]></dc:creator>
		<pubDate>Sun, 26 Feb 2023 17:33:47 +0000</pubDate>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Distributed Systems]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Peer to Peer Systems]]></category>
		<category><![CDATA[PeerBrain]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1163183</guid>

					<description><![CDATA[<p>Welcome back to the Brainwaves P2P project, or at least my take on it :-). The previous article was a theoretical explanation of how I envision this project. It is now time to start laying the groundwork! I learn as I go&#8230; As some of you might have guessed already, I’m a completely self-taught coder. ... <a title="BrainWaves P2P Social Network &#8211; How I Created a Basic Server" class="read-more" href="https://blog.finxter.com/brainwaves-p2p-social-network-how-i-created-a-basic-server/" aria-label="Read more about BrainWaves P2P Social Network &#8211; How I Created a Basic Server">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/brainwaves-p2p-social-network-how-i-created-a-basic-server/">BrainWaves P2P Social Network &#8211; How I Created a Basic Server</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Welcome back to the <a href="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" data-type="post" data-id="1132824" target="_blank" rel="noreferrer noopener">Brainwaves P2P project</a>, or at least my take on it :-). </p>



<p>The <a href="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" data-type="URL" data-id="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" target="_blank" rel="noreferrer noopener">previous article</a> was a theoretical explanation of how I envision this project. It is now time to start laying the groundwork! </p>



<h2 class="wp-block-heading">I learn as I go&#8230;</h2>



<p>As some of you might have guessed already, I’m a completely self-taught coder. Because of that, I’m sure many professionals might not agree with how I code. </p>



<p>I accept that and will welcome any constructive criticism. I have been learning non-stop since I started this project. I assume this will not slow down anytime soon. YouTube is my main source of knowledge as I learn best when seeing something done. I am, in other words, a visual learner. I found an article that explains it well here. </p>



<p>Articles on various sites are the other half of how I learn new concepts in coding. That is how I found Finxter :-).</p>



<p>So to sum it up, my code is far from perfect, and I will never claim it is. This is my take on trying to solve this puzzle. I actually look forward to alternative approaches! </p>



<p>You can <a href="https://github.com/shandralor/PeerBrain" data-type="URL" data-id="https://github.com/shandralor/PeerBrain" target="_blank" rel="noreferrer noopener">open issues on my GitHub</a> if you want to address something.</p>



<p>Now that we all know where we stand let us dive right in! <strong>How to build a server for our peer-to-peer social network app?</strong></p>



<h2 class="wp-block-heading">Flask vs FastAPI</h2>



<p>In the <a href="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" data-type="URL" data-id="https://blog.finxter.com/how-i-started-my-journey-to-help-build-a-p2p-social-network-part-1-deciding-on-a-framework/" target="_blank" rel="noreferrer noopener">previous article</a>, I mentioned that I want to use FastAPI to build the relay server, as opposed to Flask. As I have done before and will do again, I asked ChatGPT about the differences between Flask and FastAPI.</p>



<pre class="wp-block-preformatted"><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f916.png" alt="🤖" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Flask vs FastAPI</strong>

<em>Flask is based on the Werkzeug WSGI (Web Server Gateway Interface) toolkit, which is synchronous by default. However, Flask can still be used to build asynchronous applications. You will need to use a third-party library like gevent or asyncio. With these libraries, Flask can use coroutines and event loops to handle I/O operations asynchronously.</em>

<em>FastAPI, on the other hand, is designed to be fully asynchronous from the ground up. It uses the async/await syntax of Python to write asynchronous code. It is based on the ASGI (Asynchronous Server Gateway Interface) specification. FastAPI uses the Starlette framework as its foundation. the framework provides a high-performance event loop and asynchronous request handlers.</em></pre>



<p>Both the speed and the asynchrony determined my choice for FastAPI. </p>



<p>Those of you familiar with Flask will know about its built-in development server. As FastAPI doesn’t have this, we’ll need to install a separate server.</p>



<h2 class="wp-block-heading">Uvicorn Server </h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.uvicorn.org/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="747" height="468" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-350.png" alt="" class="wp-image-1163291" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-350.png 747w, https://blog.finxter.com/wp-content/uploads/2023/02/image-350-300x188.png 300w" sizes="auto, (max-width: 747px) 100vw, 747px" /></a></figure>
</div>


<p>This is where I encountered my first small hiccup. I code on Windows (I know, sue me <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f61d.png" alt="😝" class="wp-smiley" style="height: 1em; max-height: 1em;" />), and I wanted to use Uvicorn. As this only runs on Linux, I needed to get it to function in WSL. </p>



<p>I’ll not go into all the details here, but I could write something about it if anyone has an interest in it. Let me know!</p>



<p>After getting Uvicorn to function as it should, we can continue. It is important to remember that the Python interpreter on WSL does not share anything with its Windows counterpart. This means that you either need two separate virtual environments or that you install pip packages for each OS.</p>



<h2 class="wp-block-heading">Creating Basic FastAPI App</h2>



<p>Once all this annoying prep work is done, creating a basic FastAPI app is very easy. We first import FastAPI as below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from fastapi import FastAPI</pre>



<p>All you need to do afterward is define the basic app and create an endpoint.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#---APP INIT---#
app = FastAPI()
 
@app.get("/")
async def root():
    return {"message": "Hello World"}</pre>



<p>To get this to run, you need to navigate to the working directory of your FastAPI project via WSL. Afterward, you call the Uvicorn server. The command below assumes you called your Python file <code>main.py</code>!</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">uvicorn main:app --reload</pre>



<p>I usually run the Uvicorn server in a separate terminal instance of WSL. </p>



<p>That way, I can leave it on and test any changes I make immediately. Later, when I’ll be working on the client also, I can split the terminal. You can then make API calls through the client terminal window. FastAPI’s response in the server WSL window is then visible immediately.</p>



<h2 class="wp-block-heading">Receiving &#8220;Hello World&#8221; from Server</h2>



<p>If you now navigate to <code>127.0.0.1:8000</code> you should get a JSON response with the <code>"Hello World"</code> we returned in the endpoint above. We will change this endpoints function later, but for now, it works to prove our API is working.</p>



<p>For the API server, I have the following layout in mind. It might change throughout the development process. I currently foresee two endpoints that do not require the user to be logged in with a JWT token. The first will be to get that token, and the second to register a new user. Everything else will require the user to be authenticated.</p>



<p>I stated earlier that I would change the root’s endpoint function. Its new role is now to allow a user to request a JWT token. The token is only granted after providing a correct combination of username and password. This requires a dedicated set of both helper functions and Pydantic models to work. </p>



<p>I will go into this in another article, as it requires much explaining :-). It was something I am still learning myself.</p>



<h2 class="wp-block-heading">Endpoint Layout</h2>



<p>The current layout of my endpoints at a high level is the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#---OPEN ENDPOINTS---#


#Root route to get token
@app.post("/", response_model=Token)


#Route to create a new user
@app.post("/api/v1/users")


#---AUTH ENDPOINTS---#


#Route to get all current users and their attributes(development only)
@app.get("/api/v1/users")


#Route to test if the token is valid, used while authenticating
@app.get("/api/v1/token-test")


#Route to get all thoughts/messages created by a certain user
@app.get("/api/v1/thoughts/{username}")


#Route to return all thoughts/messages containing the query string
@app.get("/api/v1/thoughts/{query_str}")


#Route to create a new message/thought
@app.post("/api/v1/thoughts")


#Route to return all info about the current user(like a user profile)
@app.get("/api/v1/me", response_model=User)
</pre>



<p>The current setup should allow for the barebones functionality of the application. At least from a server point of view. The routes above and/or their function are liable to change during development.&nbsp; I do find it helps to have a visual reminder of what I am working toward. That is why I created the high-level outlay. As you might recall, I am a visual learner <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f600.png" alt="😀" class="wp-smiley" style="height: 1em; max-height: 1em;" />.</p>



<h2 class="wp-block-heading">Database Considerations</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="709" height="704" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-351.png" alt="" class="wp-image-1163293" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-351.png 709w, https://blog.finxter.com/wp-content/uploads/2023/02/image-351-300x298.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-351-150x150.png 150w" sizes="auto, (max-width: 709px) 100vw, 709px" /></figure>
</div>


<p>I will dedicate the last part of this article to the database part. As we need to store both users, user credentials, and messages/tweets somewhere, a database is a must.</p>



<p>If you have read any of my previous articles, you will know I like Deta a lot.</p>



<p>Their NoSQL databases work great for development. They recently evolved into <a href="https://deta.space/manual/apps">Deta Space</a>. This change makes their ecosystem even more interesting for developers. The fact that they are free is also important for a single developer coding this app on his own time <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f61d.png" alt="😝" class="wp-smiley" style="height: 1em; max-height: 1em;" />. Make sure to check them out!</p>



<p>The next article will focus on both the database code and the Pydantic models we will need to get our API to function.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Next Article</strong>: <a href="https://blog.finxter.com/my-journey-to-help-build-a-p2p-social-network-database-code-structure/" data-type="post" data-id="1188982" target="_blank" rel="noreferrer noopener">My Journey to Help Build a P2P Social Network – Database Code Structure</a></p>



<h2 class="wp-block-heading">Join GitHub</h2>



<p>As always, feel free to ask me questions or pass suggestions! And check out the GitHub repository for participation!</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>GitHub</strong>: <a rel="noreferrer noopener" href="https://github.com/shandralor/PeerBrain" target="_blank">https://github.com/shandralor/PeerBrain</a></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/brainwaves-p2p-social-network-how-i-created-a-basic-server/">BrainWaves P2P Social Network &#8211; How I Created a Basic Server</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>I Created a ChatGPT-Powered Website Creator with ChatGPT &#8211; Here&#8217;s What I Learned</title>
		<link>https://blog.finxter.com/i-created-a-chatgpt-powered-website-creator-with-chatgpt-heres-what-i-learned/</link>
		
		<dc:creator><![CDATA[Kevin MacNeel]]></dc:creator>
		<pubDate>Fri, 24 Feb 2023 09:17:18 +0000</pubDate>
				<category><![CDATA[ChatGPT]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1158337</guid>

					<description><![CDATA[<p>My goal with this project was to learn how to use the new Large Language Model AI GPT-3 created by OpenAI. I also wanted to know if it could be used in a practical web application. To learn it, I created a website that uses it in two ways. I also recorded this video that ... <a title="I Created a ChatGPT-Powered Website Creator with ChatGPT &#8211; Here&#8217;s What I Learned" class="read-more" href="https://blog.finxter.com/i-created-a-chatgpt-powered-website-creator-with-chatgpt-heres-what-i-learned/" aria-label="Read more about I Created a ChatGPT-Powered Website Creator with ChatGPT &#8211; Here&#8217;s What I Learned">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/i-created-a-chatgpt-powered-website-creator-with-chatgpt-heres-what-i-learned/">I Created a ChatGPT-Powered Website Creator with ChatGPT &#8211; Here&#8217;s What I Learned</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>My goal with this project was to learn how to use the new <strong><em>Large Language Model AI</em></strong> GPT-3 created by OpenAI. I also wanted to know if it could be used in a practical web application. </p>



<p>To learn it, I created a website that uses it in two ways. </p>



<ul class="wp-block-list">
<li>I used it to create the web application. </li>



<li>The web application then uses GPT-3 itself to create other simple web pages or one-page web applications. </li>
</ul>



<p>I also recorded this video that guides you through my learning experience: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f92f.png" alt="🤯" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="I Created a ChatGPT-Powered Website Creator with ChatGPT – Here’s What I Learned" width="937" height="527" src="https://www.youtube.com/embed/sfUu4sHSQA0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">A Few Words on ChatGPT</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="762" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-337-1024x762.png" alt="" class="wp-image-1158464" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-337-1024x762.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-337-300x223.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-337-768x572.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-337.png 1028w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>GPT stands for Generative Pre-trained transformer. </p>



<p>I examined its background is clearly explained in depth in its <a href="https://en.wikipedia.org/wiki/GPT-3" target="_blank" rel="noreferrer noopener">wiki article</a> and why it works is written in a <a href="https://writings.stephenwolfram.com/2023/02/what-is-chatgpt-doing-and-why-does-it-work/" target="_blank" rel="noreferrer noopener">great article</a> by Stephen Wolfram. GPT is a high-powered autocomplete that creates paragraphs and words based on their statistical association. It adds randomness to this selection, so it does not always return the same result given the same prompt.</p>



<p>&nbsp;I witnessed how it can enable great applications in multiple ways. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<ul class="has-global-color-8-background-color has-background wp-block-list">
<li><strong>ChatGPT Usage 1</strong>: Text autocompletes can be used superbly to write well-written code.&nbsp; </li>



<li><strong>ChatGPT Usage 2</strong>: It can also be used in the application to enable or enhance its functionality.&nbsp; </li>



<li><strong>ChatGPT Usage 3</strong>: The coder can also use it to expedite learning and create new code. </li>
</ul>



<p>In creating the website, I found the latter to be the most useful.</p>



<p>This article guides you through how I used and created a website that can generate a website from a text prompt. <a href="https://openai.com/api/" target="_blank" rel="noreferrer noopener">Open AI’s GPT Da Vinci</a> powers the site. I used Open AI’s <a href="https://chat.openai.com/chat" target="_blank" rel="noreferrer noopener">Chat GPT</a> to create much of its code.&nbsp; </p>



<p>I also used GPT-3 based ghostwriter code assistant in the <a rel="noreferrer noopener" href="https://replit.com/" target="_blank">Replit</a> IDE or interactive development environment for auto-completion. I also examine how I used prompt engineering for development, Flask, and JavaScript to create its functionality.&nbsp;</p>



<h2 class="wp-block-heading">The GPT-3 Website Prototyper Site</h2>



<p>Here’s an example of what the site looks like:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="508" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-329-1024x508.png" alt="" class="wp-image-1158346" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-329-1024x508.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-329-300x149.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-329-768x381.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-329-1536x762.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/02/image-329.png 1600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Here’s an example of a pong game created with it just from entering the above prompt text:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="733" height="533" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-330.png" alt="" class="wp-image-1158347" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-330.png 733w, https://blog.finxter.com/wp-content/uploads/2023/02/image-330-300x218.png 300w" sizes="auto, (max-width: 733px) 100vw, 733px" /></figure>
</div>


<h2 class="wp-block-heading">How the Application Works</h2>



<p>Let’s first see what the site does before we look into its code.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="883" height="691" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-338.png" alt="" class="wp-image-1158468" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-338.png 883w, https://blog.finxter.com/wp-content/uploads/2023/02/image-338-300x235.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-338-768x601.png 768w" sizes="auto, (max-width: 883px) 100vw, 883px" /></figure>
</div>


<p>Here’s the site&nbsp;<a href="https://web-prototyper.kevron.repl.co/">https://web-prototyper.kevron.repl.co/</a>. Go to the site and enter a prompt.&nbsp;&nbsp;</p>



<p>Here are some example prompts:</p>



<ul class="wp-block-list">
<li><em>“Create an HTML pong game with javascript and an AI”</em></li>



<li><em>“Create an HTML page with street address, zip code, first name, last name, and a date picker for the birthdate.”</em></li>
</ul>



<p>Here’s a <a rel="noreferrer noopener" href="https://help.openai.com/en/articles/6654000-best-practices-for-prompt-engineering-with-openai-api" target="_blank">site</a> that gives you information on prompt engineering from OpenAI. If you want to create a website, you’ll have some keywords like &#8220;JavaScript&#8221; and &#8220;HTML&#8221;. In addition, you can add CSS and colors to your site.&nbsp;</p>



<p>Then Click on the <code>Create</code> button that gets the output from the <strong><em>GPT API Davinci</em></strong>. Enter a name. Then save. </p>



<p>You can click on the link to go to the site. You can also click on the code to view the code. You should remember that the code it generates has some randomness to it, and it won’t always return the same result.</p>



<p><em>If you want to learn more about using ChatGPT as the logic of your own apps, feel free to check out the Finxter premium course here:</em> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://academy.finxter.com/university/chatgpt-at-the-heart-building-a-movie-recommendation-python-web-app-in-2023/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="922" height="335" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-348.png" alt="" class="wp-image-1160876" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-348.png 922w, https://blog.finxter.com/wp-content/uploads/2023/02/image-348-300x109.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-348-768x279.png 768w" sizes="auto, (max-width: 922px) 100vw, 922px" /></a></figure>
</div>


<h2 class="wp-block-heading">How I Created the GPT-3 Website Prototyper Site</h2>



<p>I wrote some of this website&#8217;s code using Chat-GPT and then manually put the pieces together. </p>



<p>This is a gap in the AIs and where the programmers come in. They can’t see the big picture and put together pieces of code from different sites like </p>



<ul class="wp-block-list">
<li>Stack Overflow, </li>



<li>Google, </li>



<li>Finxter, and </li>



<li>Chat GPT. </li>
</ul>



<p>Chat GPT, on the other hand, can only use code already processed on its site.&nbsp; Throughout the creation of this site, I used these sources to look up how to create this site. I could not just use Chat GPT.&nbsp; </p>



<p>One of the current gaps humans can fill that Chat generators can’t, even though they are impressive, is tying large pieces and concepts together accurately. So I had to manually tie together the front end, backend, and saving functionality.</p>



<p>Here’s the prompt used to create the Flask backend.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="980" height="205" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-332.png" alt="" class="wp-image-1158433" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-332.png 980w, https://blog.finxter.com/wp-content/uploads/2023/02/image-332-300x63.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-332-768x161.png 768w" sizes="auto, (max-width: 980px) 100vw, 980px" /></figure>
</div>


<p>This generated back-end Flask python code and JavaScript code, the JavaScript code called the Flask backend.</p>



<p>I modified the code to work with my site, but the basic structure of the code is from what was generated by OpenAI. I was not familiar with Flask. I’m a professional web developer, though. The ChatGPT, the <a href="https://blog.finxter.com/build-website-with-flask/" data-type="post" data-id="420533" target="_blank" rel="noreferrer noopener">Finxter tutorial</a>, and my experience helped me get up to speed with Flask in minutes.&nbsp;&nbsp;</p>



<p>The code for the application can be found on <a href="https://replit.com/@kevron/Web-Prototyper" target="_blank" rel="noreferrer noopener">Replit </a>and <a href="https://github.com/finxter/Web-Prototyper" data-type="URL" data-id="https://github.com/finxter/Web-Prototyper" target="_blank" rel="noreferrer noopener">Github</a>. I’ll post links to the Replit because I believe it gives you the best ability to run and fork the code.&nbsp;</p>



<p>The communication of the API is the Python code here (<a href="https://replit.com/@kevron/Web-Prototyper#main.py" data-type="URL" data-id="https://replit.com/@kevron/Web-Prototyper#main.py" target="_blank" rel="noreferrer noopener">Replit</a>):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def gpt3_request():
  data = request.get_json()
  prompt = data['prompt']
  completions = openai.Completion.create(
    engine="text-davinci-002",
    prompt=prompt,
    max_tokens=4000,
    n=1,
    stop=None,
    temperature=0.5,
  )

  message = completions.choices[0].text
  print(message)

  return jsonify({'message': message})</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="566" height="447" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-333.png" alt="" class="wp-image-1158442" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-333.png 566w, https://blog.finxter.com/wp-content/uploads/2023/02/image-333-300x237.png 300w" sizes="auto, (max-width: 566px) 100vw, 566px" /></figure>
</div>


<p>It’s called by the JavaScript code here, which parses the HTML. You can see the code below.&nbsp;</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="712" height="729" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-334.png" alt="" class="wp-image-1158447" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-334.png 712w, https://blog.finxter.com/wp-content/uploads/2023/02/image-334-293x300.png 293w" sizes="auto, (max-width: 712px) 100vw, 712px" /></figure>
</div>


<p>It does this to organize the code into CSS, HTML, and JavaScript. It’ll later be injected back into the DOM of a new page. I did this step because the JavaScript and CSS were not always well-formed, so I wanted to separate them out.</p>



<p>I used Chat GPT and StackOverflow. I used StackOverflow to find a technique to help me determine which one to <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/5924485/how-is-indexeddb-conceptually-different-from-html5-local-storage" target="_blank">use</a>.&nbsp;I used Stackoverflow to determine what JavaScript technique I should use to save it in the database. </p>



<p>I like StackOverflow because there is a human voting mechanism. It also has feedback and different perspectives and opposing sides.&nbsp; This is something that ChatGPT misses. It’s only one source</p>



<p>Here’s the prompt I used on ChatGPT to show me the JavaScript client-side database code</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="888" height="140" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-335.png" alt="" class="wp-image-1158454" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-335.png 888w, https://blog.finxter.com/wp-content/uploads/2023/02/image-335-300x47.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-335-768x121.png 768w" sizes="auto, (max-width: 888px) 100vw, 888px" /></figure>
</div>


<p>&nbsp;I knew I had to save it for the client. Here’s some of the code to save to the client</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="742" height="651" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-336.png" alt="" class="wp-image-1158455" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-336.png 742w, https://blog.finxter.com/wp-content/uploads/2023/02/image-336-300x263.png 300w" sizes="auto, (max-width: 742px) 100vw, 742px" /></figure>
</div>


<p>You can see the full code here: <a href="https://replit.com/@kevron/Web-Prototyper#static/post.js" target="_blank" rel="noreferrer noopener">https://replit.com/@kevron/Web-Prototyper#static/post.js</a></p>



<p>It is about 75% of the same code as what I got from Chat-GPT-3 .&nbsp;</p>



<p>The technologies used are Replit for the IDE, OpenAI DaVinci, Python and flask for the backend, HTML and javascript, GIT for source control, and Chat-GPT3.</p>



<h2 class="wp-block-heading">Understanding the Security, Safety Concerns, and Limitations</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="667" height="441" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-339.png" alt="" class="wp-image-1158469" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-339.png 667w, https://blog.finxter.com/wp-content/uploads/2023/02/image-339-300x198.png 300w" sizes="auto, (max-width: 667px) 100vw, 667px" /></figure>
</div>


<p>This a powerful technology, and I think there are both security and safety concerns that I learned about from using GPT 3 and reading articles about it.</p>



<p>The security concern in this app is that I can now generate tons of HTML pages if I want to. What if some of the information on this site is unsafe or inaccurate? The potential for the inaccuracy of the data is mentioned on many sites. This technology needs to be used <a rel="noreferrer noopener" href="https://platform.openai.com/docs/guides/safety-best-practices" target="_blank">safely</a> from OpenAI. </p>



<p>Since this is a new powerful and new technology, many other new safety concerns may arise. I think it’ll vary depending on the organizations&#8217; specific use of GPT.</p>



<p>They lack the ability to <a href="https://www.sciencetimes.com/articles/42482/20230220/human-beats-artificial-intelligence-go-prof-stuart-j-russell-highlights.htm" target="_blank" rel="noreferrer noopener">generalize </a>and see the big picture.&nbsp;</p>



<p>Also, the data is stored in the browser&#8217;s database. It should not be modified and open to store the HTML code from the website. It could be an internal company tool, though. It’s ok when it is run on the client, but saving this in the database could be dangerous and open up cross-site scripting concerns. </p>



<p>For example, it could be saved in GitHub or saved in someone else’s database.</p>



<h2 class="wp-block-heading">My Conclusions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="604" height="894" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-340.png" alt="" class="wp-image-1158470" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-340.png 604w, https://blog.finxter.com/wp-content/uploads/2023/02/image-340-203x300.png 203w" sizes="auto, (max-width: 604px) 100vw, 604px" /></figure>
</div>


<p>This technology is super exciting and will empower many people to create things from just an idea. </p>



<p><a href="https://www.cnbc.com/2023/02/10/bill-gates-says-ai-like-chatgpt-is-the-most-important-innovation.html" target="_blank" rel="noreferrer noopener">Bill Gates</a> and other large investors have said this technology is transformative. Companies such as Google and Microsoft are investing millions of dollars in it.&nbsp; </p>



<p>Despite the safety concerns of GPT and some of its limitations, I’m very excited about working with this technology and other assistive AI technology in the future. </p>



<p>It helped me immensely in writing this code. </p>



<p>I’m also optimistic that some of its criticisms of accuracy are being worked on and addressed. </p>



<p>I learned through writing this article how powerful and helpful GPT can be as an assistive tool. I also learned firsthand that while GPT is powerful, it does not seem like it will replace a human programmer. It cannot generalize, see the big picture, and fact-check like a human does from multiple sources. </p>



<p>So I hope that in following this article, you’ve developed knowledge about GPT and learned how to use it as a code generation tool too. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://academy.finxter.com/university/chatgpt-at-the-heart-building-a-movie-recommendation-python-web-app-in-2023/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="922" height="335" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-348.png" alt="" class="wp-image-1160876" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-348.png 922w, https://blog.finxter.com/wp-content/uploads/2023/02/image-348-300x109.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-348-768x279.png 768w" sizes="auto, (max-width: 922px) 100vw, 922px" /></a></figure>
</div><p>The post <a href="https://blog.finxter.com/i-created-a-chatgpt-powered-website-creator-with-chatgpt-heres-what-i-learned/">I Created a ChatGPT-Powered Website Creator with ChatGPT &#8211; Here&#8217;s What I Learned</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ChatGPT at the Heart &#8211; Building a Movie Recommendation Python Web App in 2023</title>
		<link>https://blog.finxter.com/building-a-movie-recommendation-app-with-chatgpt/</link>
		
		<dc:creator><![CDATA[Rafal Kaluzny]]></dc:creator>
		<pubDate>Tue, 14 Feb 2023 16:05:45 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[ChatGPT]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1132950</guid>

					<description><![CDATA[<p>In this article, I will show you how I have built a simple but quite powerful movie recommendation app. 💻 Try It Yourself: You can play with the live demo here. I built it for two reasons: This app uses Python, HTML/CSS, Flask, Vercel, and the OpenAI API capabilities. Prerequisites Files in this project Here ... <a title="ChatGPT at the Heart &#8211; Building a Movie Recommendation Python Web App in 2023" class="read-more" href="https://blog.finxter.com/building-a-movie-recommendation-app-with-chatgpt/" aria-label="Read more about ChatGPT at the Heart &#8211; Building a Movie Recommendation Python Web App in 2023">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/building-a-movie-recommendation-app-with-chatgpt/">ChatGPT at the Heart &#8211; Building a Movie Recommendation Python Web App in 2023</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, I will show you how I have built a simple but quite powerful movie recommendation app.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4bb.png" alt="💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Try It Yourself</strong>: <a href="https://vercel-openai.vercel.app/" data-type="URL" data-id="https://vercel-openai.vercel.app/" target="_blank" rel="noreferrer noopener">You can play with the live demo here.</a></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Building a Movie Recommendation Python App with ChatGPT" width="937" height="703" src="https://www.youtube.com/embed/6xHg66qGjdQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>I built it for two reasons: </p>



<ul class="wp-block-list">
<li>(i) to keep educating myself on modern technologies, </li>



<li>(ii) to see which movies can entertain me on a weekend night.</li>
</ul>



<p>This app uses Python, HTML/CSS, Flask, Vercel, and the OpenAI API capabilities.</p>



<h2 class="wp-block-heading">Prerequisites</h2>



<ul class="wp-block-list">
<li>Python with <strong><code><a href="https://blog.finxter.com/build-website-with-flask/" data-type="post" data-id="420533" target="_blank" rel="noreferrer noopener">flask</a></code></strong> and <strong><code><a href="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/" data-type="post" data-id="1081478" target="_blank" rel="noreferrer noopener">openai</a></code></strong> libraries</li>



<li>OpenAI secret key from<br><a rel="noreferrer noopener" href="https://beta.openai.com/account/api-keys" target="_blank">https://beta.openai.com/account/api-keys<br></a>(see a nice <a rel="noreferrer noopener" href="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent" data-type="URL" data-id="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent" target="_blank">Finxter tutorial</a> on how to get it)</li>



<li>Vercel account for cloud deployment<br><a href="https://vercel.com/" target="_blank" rel="noreferrer noopener">https://vercel.com/</a></li>



<li>GitHub account for code storage<br>Feel free to use/fork the below code from the <a rel="noreferrer noopener" href="https://github.com/finxter/vercel-openai" data-type="URL" data-id="https://github.com/finxter/vercel-openai" target="_blank">GitHub</a></li>
</ul>



<h2 class="wp-block-heading">Files in this project</h2>



<p>Here is the snapshot of my code from GitHub.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="930" height="924" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-192.png" alt="" class="wp-image-1132962" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-192.png 930w, https://blog.finxter.com/wp-content/uploads/2023/02/image-192-300x298.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-192-150x150.png 150w, https://blog.finxter.com/wp-content/uploads/2023/02/image-192-768x763.png 768w" sizes="auto, (max-width: 930px) 100vw, 930px" /></figure>
</div>


<p>The key files are these:</p>



<ul class="wp-block-list">
<li><code>.env</code></li>



<li><code>api/index.py</code></li>



<li><code>api/templates/index.html</code></li>
</ul>



<p>First, I use the <code>.env</code> file and add my secret key.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">FLASK_APP=app
FLASK_DEBUG=1
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</pre>



<p>Then goes the Python file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os, openai
from flask import Flask, redirect, render_template, request, url_for


app = Flask(__name__)
openai.api_key = os.getenv("OPENAI_API_KEY")




@app.route("/", methods=("GET", "POST"))
def index():
   if request.method == "POST":
       category = request.form["category"]
       number = request.form["number"]
       response = openai.Completion.create(
           model="text-davinci-003",
           prompt=generate_prompt(number, category),
           temperature=0.5,
           max_tokens=60,
           top_p=1,
           frequency_penalty=0,
           presence_penalty=0
       )


       return redirect(url_for("index", result=response.choices[0].text))


   result = request.args.get("result")
   return render_template("index.html", result=result)




def generate_prompt(number, category):
   return """Recommend the best {} {} movies to watch:""".format(number,
       category.capitalize()
   )






if __name__ == '__main__':
   app.run(host='127.0.0.1', port=5050, debug=True)
</pre>



<p>The imports I use are the following:</p>



<ul class="wp-block-list">
<li><code><a href="https://blog.finxter.com/exploring-pythons-os-module/" data-type="post" data-id="19050" target="_blank" rel="noreferrer noopener">os</a></code> &#8211; to work with the functionality dependent on the operating system</li>



<li><code><a href="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/" data-type="post" data-id="1081478" target="_blank" rel="noreferrer noopener">openai</a></code> &#8211; to get the best of OpenAI artificial intelligence</li>



<li><code><a href="https://blog.finxter.com/build-website-with-flask/" data-type="post" data-id="420533" target="_blank" rel="noreferrer noopener">flask</a></code> &#8211; to have a nice-looking frontend framework for Python</li>
</ul>



<p>Some Flask basics.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@app.route("/", methods=("GET", "POST"))</pre>



<p>The first line there is implementing the main route (and the only one in this app). You can think of it as the main URL, whether it is <code>localhost/</code> or <code>www.mysite.com/</code>.</p>



<p>The following function <code>index()</code> is taking information from the HTML form (see <code>index.html</code>) and preparing the data to be displayed back by the <code>index.html</code> site.</p>



<p>Here’s what happens the moment you hit the “<code>Generate titles</code>” button on your site:</p>



<ul class="wp-block-list">
<li><code>index()</code> function takes the input being “number” and “category” from the form,</li>



<li>feeds it into the <code>generate_prompt()</code> function,&nbsp;</li>



<li>which crafts and passes back a question to be asked,</li>



<li>which then &#8211; via the API &#8211; is sent to OpenAI to get a “response”,&nbsp;</li>



<li>that is then passed as “result” onto <code>index.html</code> to render on the screen.</li>
</ul>



<p>Let’s also have a look at the <code>index.html</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;head>
 &lt;title>OpenAI Movies&lt;/title>
 &lt;link
   rel="shortcut icon"
   href="{{ url_for('static', filename='movie.png') }}"
 />
 &lt;link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}" />
&lt;/head>


&lt;body>
 &lt;img src="{{ url_for('static', filename='movie.png') }}" class="icon" />
 &lt;h3>Recommend the top movies&lt;/h3>
 &lt;form action="/" method="post">
   &lt;input type="text" name="number" placeholder="How many proposals, e.g. 1,3,10" required />
   &lt;input type="text" name="category" placeholder="Enter the category e.g. thriller, comedy" required />
   &lt;input type="submit" value="Generate titles" />
 &lt;/form>
 {% if result %}
 &lt;div class="result">
   &lt;pre>{{ result | safe }}&lt;/pre>
 &lt;/div>
 {% endif %}
&lt;/body>
</pre>



<p>I will not go over the HTML tags as these should be familiar to you, and if not, you can get yourself up to speed with that using other web sources.</p>



<p>Initially, the file will feel like an ordinary HTML/CSS site, but after a while, you will notice a strange animal.&nbsp; It is placed here at the bottom of the file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> {% if result %}
 &lt;div class="result">
   {{ result }}
 &lt;/div>
 {% endif %}
</pre>



<p>This is where Python co-exists with HTML and allows the “result” that we generate in our “Python backend” to be passed over to the “Flask frontend”. If it exists, the flask engine will render the website with the results at the bottom.</p>



<h2 class="wp-block-heading">Run the App Locally</h2>



<p>Running an app is simple. I just run the <code>index.py</code> file.</p>



<p>With the “<code>host</code>” and “<code>port</code>” attributes specified in the <code>index.py</code> file, Flask will run a local web server with the site.</p>



<p>This is how it looks in my Visual Studio Code:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="637" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-193-1024x637.png" alt="" class="wp-image-1132977" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-193-1024x637.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-193-300x187.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-193-768x478.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-193-1536x955.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/02/image-193.png 1600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>And this is the browser view:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="581" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-194-1024x581.png" alt="" class="wp-image-1132978" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-194-1024x581.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-194-300x170.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-194-768x436.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-194-1536x872.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/02/image-194.png 1600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h2 class="wp-block-heading">Vercel deployment</h2>



<p>Alright, the app is built and works fine on my local machine.&nbsp;</p>



<p>Now &#8211; let’s get it shipped to the world!</p>



<p>First, I put the whole project into my <a rel="noreferrer noopener" href="https://github.com/finxter/vercel-openai" data-type="URL" data-id="https://github.com/finxter/vercel-openai" target="_blank">personal GitHub repo</a>. I am using a public one just so that you and other readers can use it. Yet, if you follow my steps here, I would suggest a private one to you.<br></p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f6d1.png" alt="🛑" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Warning</strong>: The risk with public repo is that it exposes your OpenAI secret key to the world! That would be identified anyways, and your key would rotate, but why bother?</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="607" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-195-1024x607.png" alt="" class="wp-image-1132980" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-195-1024x607.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-195-300x178.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-195-768x456.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-195-1536x911.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/02/image-195.png 1600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Now, I log in to the Vercel dashboard and click on “Add New…” and select “Project”.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="353" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-196-1024x353.png" alt="" class="wp-image-1132982" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-196-1024x353.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-196-300x103.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-196-768x264.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-196-1536x529.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/02/image-196.png 1600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Selecting GitHub as Git provider.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="717" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-197-1024x717.png" alt="" class="wp-image-1132983" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-197-1024x717.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-197-300x210.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-197-768x538.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-197.png 1422w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Selecting the repository and importing it.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="666" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-198-1024x666.png" alt="" class="wp-image-1132984" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-198-1024x666.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-198-300x195.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-198-768x499.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-198.png 1406w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Arrived at the “<strong>You&#8217;re almost done.</strong>” page. There is no need to alter any of the default parameters there except adding one important variable. In environment variables, I add my own unique <code>OPENAI_API_KEY</code>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="399" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-199-1024x399.png" alt="" class="wp-image-1132986" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-199-1024x399.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-199-300x117.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-199-768x299.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-199-1536x598.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/02/image-199.png 1600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Making sure this is indeed saved properly.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="109" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-200-1024x109.png" alt="" class="wp-image-1132987" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-200-1024x109.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-200-300x32.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-200-768x82.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-200-1536x164.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/02/image-200.png 1600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>This is it. Hitting “Deploy” and watching the wheels spin.</p>



<p>Vercel builds it for me and assigns some public domains to the app.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="506" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-201-1024x506.png" alt="" class="wp-image-1132993" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-201-1024x506.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/02/image-201-300x148.png 300w, https://blog.finxter.com/wp-content/uploads/2023/02/image-201-768x380.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-201-1536x759.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/02/image-201.png 1600w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Once I arrive at the final page, I open up the app, test it again and if all works ok, share with the family &amp; friends &amp; Finxter readers!&nbsp;</p>



<p>If you liked this journey, you can <a href="https://github.com/ralpho79/vercel-openai" data-type="URL" data-id="https://github.com/ralpho79/vercel-openai" target="_blank" rel="noreferrer noopener">give me a star in my GitHub repo</a> or this article <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" />&nbsp;</p>



<p>Any doubts or comments, drop me a line.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4bb.png" alt="💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Try It Yourself</strong>: <a href="https://vercel-openai.vercel.app/" data-type="URL" data-id="https://vercel-openai.vercel.app/" target="_blank" rel="noreferrer noopener">You can play with the live demo here.</a></p>



<p>Happy coding!</p>



<h2 class="wp-block-heading">Get Your Personal Certificate Proving Your ChatGPT-Powered Coding Skills</h2>



<p>If you&#8217;re a premium member, you can also go through <a rel="noreferrer noopener" href="https://academy.finxter.com/university/chatgpt-at-the-heart-building-a-movie-recommendation-python-web-app-in-2023/" data-type="URL" data-id="https://academy.finxter.com/university/chatgpt-at-the-heart-building-a-movie-recommendation-python-web-app-in-2023/" target="_blank">this mini-course project on the Finxter Academy</a> and certify your newly-acquired skills. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://academy.finxter.com/university/chatgpt-at-the-heart-building-a-movie-recommendation-python-web-app-in-2023/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="880" height="1024" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-202-880x1024.png" alt="" class="wp-image-1133475" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-202-880x1024.png 880w, https://blog.finxter.com/wp-content/uploads/2023/02/image-202-258x300.png 258w, https://blog.finxter.com/wp-content/uploads/2023/02/image-202-768x894.png 768w, https://blog.finxter.com/wp-content/uploads/2023/02/image-202.png 915w" sizes="auto, (max-width: 880px) 100vw, 880px" /></a></figure>
</div>


<p>I&#8217;m sure many employers and clients would love to hire coders that can use the latest technological disruptions to build advanced applications (that are also easy to develop). <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://blog.finxter.com/building-a-movie-recommendation-app-with-chatgpt/">ChatGPT at the Heart &#8211; Building a Movie Recommendation Python Web App in 2023</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-06-05 21:49:21 by W3 Total Cache
-->