How to Build a Simple Web App With Python and Flask
Python and Flask: The Perfect Duo for Building Your First Web App

Web development is a popular and rewarding field that allows you to create dynamic and interactive websites and applications. One of the most widely used tools for web development is Python, a versatile and powerful programming language.
Python has many frameworks that simplify and speed up the development process, such as Flask. Flask is a microframework that provides the essential features for building web apps, such as routing, templating, and testing.
Setting up the environment
Before you start coding, you need to set up your environment. You need to have Python installed on your computer. You can download it from the official website: https://www.python.org/downloads/.
You also need to install Flask, which is a Python package that contains the Flask framework. You can install Flask using pip, which is a tool that manages Python packages. To install Flask, open your terminal or command prompt and type:
pip install Flask
You also need to create a virtual environment for your project. A virtual environment is a separate space where you can install and manage the packages that your project needs, without affecting other projects or the system.
To create a virtual environment, you can use venv, which is a module that comes with Python. To create a virtual environment, type:
python -m venv venv
This will create a folder called venv in your current directory. To activate the virtual environment, type:
source venv/bin/activate (on Linux or Mac)
venv\Scripts\activate (on Windows)
You should see (venv) at the beginning of your prompt, indicating that you are in the virtual environment. To deactivate it, type:
deactivate
Finally, you need to install the dependencies that your project needs. For this tutorial, you only need one dependency: requests. Requests is a library that allows you to make HTTP requests in Python. You can install requests using pip:
- pip install requests
- Creating the app
App Creation
Now that you have set up your environment, you can start creating your app. First, you need to create a new Flask app. To do this, create a file called app.py in your project folder and write the following code:
from flask import Flask
app = Flask(__name__)
This imports the Flask class from the flask package and creates an instance of it called app. This instance represents your web app and handles all the requests and responses.
Next, you need to create a route that displays a greeting message. A route is a function that defines what happens when a user visits a specific URL. To create a route, you use the app.route decorator, which takes the URL as an argument and registers the function as a handler for that URL. For example, to create a route for the home page (/), write:
@app.route('/')
def index():
return 'Hello, world!'
This defines a function called index that returns 'Hello, world!' as the response when someone visits the home page.
Next, you need to create another route that displays a random quote. To do this, you need to use the requests library to fetch some quotes from an API.
An API is an interface that allows you to communicate with other applications or services over the internet. For this tutorial, you will use the Quotable API (https://api.quotable.io/), which provides random quotes from famous authors. To create a route for the quotes page (/quotes), write:
import requests
@app.route('/quotes')
def quotes():
response = requests.get('https://api.quotable.io/random')
data = response.json()
quote = data['content']
author = data['author']
return f'{quote} - {author}'
This imports the requests library and defines a function called quotes that makes a GET request to the Quotable API and gets a random quote as JSON data. JSON is a format that represents data as key-value pairs. The function then extracts the content and author fields from the data and returns them as the response.
Styling the app
Now that we have created the basic functionality of our web app, we can make it look more appealing by adding some CSS. CSS stands for Cascading Style Sheets and it is a language that defines how HTML elements are displayed on a web page.
To use CSS in our Flask app, we need to create a static folder inside our project directory and place a style.css file inside it. The static folder is where we store any files that are not related to the logic of our app, such as images, fonts, or scripts.
In the style.css file, we can write some rules to customize the appearance of our app. For example, we can change the background color, the font family, and the text alignment of our app. We can also add some margins and padding to create some space around our elements.
Here is an example of how our style.css file could look like:
css
body { background-color: #f0f0f0; font-family: Arial, sans-serif; text-align: center; }
h1 { color: #333333; margin-top: 50px; }
p { color: #666666; margin-bottom: 50px; }
.quote { font-style: italic; } ```
To apply the CSS rules to our HTML template, we need to link the style.css file in the head section of our index.html file. We can use the url_for function to generate the correct path to the static folder. Here is how our index.html file could look like after adding the link:
```html
<html> <head> <title>Simple Web App</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head> <body> <h1>Welcome to our simple web app!</h1>
<p>This app was built with Python and Flask.</p>
<p>Here is a random quote for you:</p>
<p class="quote">{{ quote }}</p>
</body>
</html>
```
Now, if we run our app again and refresh our browser, we should see a more attractive web page with our custom styles.
Testing the app
Before we deploy our app to the web, we need to test it locally to make sure it works as expected. To run the app locally, we need to set an environment variable called FLASK_APP to the name of our Python file. In our case, it is app.py. We can do this by typing the following command in the terminal:
export FLASK_APP=app.py
Then, we can start the app by typing:
flask run
This will launch a local server that hosts our app. We can access it by opening a web browser and typing http://localhost:5000 in the address bar. We should see our greeting message and a random quote displayed on the screen. We can refresh the page to see different quotes.
Deploying the app
Now that we have tested our app locally, we are ready to deploy it to the web. There are many ways to deploy a Flask app, but one of the easiest and most popular ones is to use a cloud platform like Heroku or AWS. In this article, we will use Heroku as an example.
To deploy our app to Heroku, we need to create a Heroku account and install the Heroku CLI tool. Then, we need to create a file called Procfile in our project folder. This file tells Heroku how to run our app. The content of the file should be:
web: gunicorn app:app
This means that we are using gunicorn as our web server and app:app as our entry point.
Next, we need to create a file called requirements.txt in our project folder. This file lists all the dependencies that our app needs. The content of the file should be:
- Flask
- gunicorn
- requests
Then, we need to create a Git repository for our project and push it to Heroku. We can do this by typing the following commands in the terminal:
git init
git add .
git commit -m "Initial commit"
heroku create
git push heroku master
This will create a new app on Heroku and deploy our code to it. We can check the status of our deployment by typing:
heroku logs --tail
We should see some messages indicating that our app is running. We can also open our app in a web browser by typing:
heroku open
We should see our app running on the web with a URL like https://<app-name>.herokuapp.com.
If you want to learn more about Python and Flask, here are some additional resources that you might find useful:
- The official Flask documentation: https://flask.palletsprojects.com/en/2.0.x/
- A comprehensive Flask tutorial by Miguel Grinberg: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
- A free course on Python web development by Corey Schafer: https://www.youtube.com/playlist?list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH
- A book on Flask web development by Miguel Grinberg: https://www.amazon.com/Flask-Web-Development-Developing-Applications/dp/1491991739
About the Creator
Nelis Thuo
Welcome to my world of words! I am a lover of all things literature and storytelling. Join me on my journey as I explore the depths of the human experience and uncover the beauty in the everyday.



Comments
There are no comments for this story
Be the first to respond and start the conversation.