This introductory Python Flask tutorial explains what is Flask, installation of Python, Virtualenv, Flask Hello World example with a section on code examples, debugging, and testing:
Website development is more of an art than a skill. It requires patience and diligence, along with perseverance, courage, and dedication to create what’s necessary for it to be a real success. These days, it is essential for learners to get to speed as soon as possible.
We have created this Python Flask tutorial for the students to get up to speed and implement simple as well as complex web programming using Python 3.
This Python Flask tutorial is more like a flask beginner tutorial, which will cover the installation of Python, Virtualenv, and other essential packages. In this series of tutorials, we will also install Flask along with the other necessary Flask plugins. We have also included a section on code debugging, testing, and continuous integration using Git Actions.
Table of Contents:
List Of Tutorials In This Flask Series
Tutorial #1: Python Flask Tutorial – Introduction To Flask For Beginners
Tutorial #2: Flask Template, Form, View, And Redirect With Examples
Tutorial #3: Flask Database Handling – How To Use Flask With A Database
Tutorial #4: Flask App And Flask Project Layout With Blueprint & Bootstrap
Tutorial #5: Flask Design Patterns And Best Practices For Web Applications
Tutorial #6: Flask API Tutorial With Example | Extending Flask With APIs
Tutorial #7: Django Vs Flask Vs Node: Which Framework To Select
Tutorial #8: Top 31 Popular Python Flask Interview Questions With Answers
What Is Flask
Flask is a web development framework. It is a framework with a built-in development server and a debugger.
Flask framework in itself is different from the other archetypes as it allows web developers to be flexible and to comfortably accommodate the frequently released changes in the software development community.
What Is Flask Used For
We use the Flask framework for developing Web Applications in Python programming language. It integrates with other third-party services and APIs to bring richness and meaning to the application under development. Flask’s core concepts are simple, and it has a tiny footprint.
Let’s start with this Python Flask tutorial to understand web development with the help of a Flask GitHub repository. However, before proceeding, please clone the project from Github for easy follow up on the discussed code examples.
Prerequisites
Other than the mentioned headings in this section, we recommend creating a Github Account. Let’s proceed with the below-mentioned steps in the prerequisites.
Step 1: Install Python
Check whether you have installed Python 3 or not. If not, then download Python 3 from here and install it as per your Operating System.
Step 2: Create a Python Virtual Environment
Create a virtual environment using the below command.
python3 -m venv venv
Use the below command to activate the Python virtual environment.
source venv/bin/activate
We have given an example of activation and deactivation of the virtual environment below.
All the subsequent commands in this tutorial should run in an activated virtual environment. Install the wheel package so that we can build wheels inside the virtual environment.
pip install wheel
Step 3: Flask Download And Insall
We need to perform the Flask download steps and install Flask using the below-mentioned steps.
Now install Flask.
pip install flask
Some of us like to work along with the latest source code changes. We can use the below-given command to install with the latest changes to the sources of Flask.
Make a temporary directory.
mkdir tmp
Now install Flask from the Github repository. You need to remain connected to the internet for the below command to work.
pip3 install -e git+git@github.com:pallets/flask.git#egg=flask
Look at the console outputs to check the successful installation. Now check if we can access Flask commands.
flask --help
You might see some exceptions about the absence of a Flask application. However, neglect those as we have not created any Flask app. Our app is an instance of Flask, which is a wrapper on the Werkzeug web framework and Jinja templating engine.
Werkzeug
Werkzeug is a WSGI toolkit. WSGI is only a calling convention for web servers to forward web requests to web applications written in Python programming language.
Jinja
Templating is an essential skillset of web developers. Jinja is a fully-featured and popular templating engine for Python. It is quite an expressive language and provides a robust set of tools to template authors.
Step 4: Install MongoDB
Follow the below-mentioned steps to install MongoDB. We have outlined the steps to install it in a Debian based Linux. If you are using another operating system, then access the link and install as per the intended operating system.
Install gnupg for importing MongoDB public GPG key.
sudo apt-get install gnupg
Now import the key using the command below.
wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -
Create the sources list file as per your Linux distribution. We have added the list of sources as per Debian.
echo "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/4.2 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
Run update command
sudo apt-get update
Now install MongoDB, using the below command.
sudo apt-get install -y mongodb-org
Once the installation is successful, start MongoDB using the below command.
sudo systemctl start mongod
Check the status of MongoDB, using the command below.
sudo systemctl status mongod
Now ensure that mongod automatically starts at system reboot by issuing the below-shown command.
sudo systemctl enable mongod
Now check if you can connect to the MongoDB server using mongo client.
mongo
In the mongo shell, try using the help and show dbs commands.
Create A Flask App
Use the command below to install flask-appbuilder and mongoengine.
pip install flask-appbuilder pip install mongoengine pip install flask_mongoengine
Create a skeleton app with the values shown as comments in the below code snippet.
flask fab create-app # Give the following values in the command line questionnaire # Application Name: flaskTutorialApp # EngineType : MongoEngine
We will see the output similar to the one given below.
Your new app name: exampleApp Your engine type, SQLAlchemy or MongoEngine (SQLAlchemy, MongoEngine) [SQLAlchemy]: MongoEngine Downloaded the skeleton app, good coding!
Have a look at the layout of the project and the app. We have shown the output of the tree command below.
Let’s have a look at the Flask config file. It is a default config generated as the result of the last command. Uncomment Cyborg theme, as shown below.
# Theme configuration for Cybord=g # these themes are located on static/appbuilder/css/themes # We can create our own and easily use them by placing them on the same dir structure to override #APP_THEME = "bootstrap-theme.css" # default bootstrap #APP_THEME = "cerulean.css" # cerulean #APP_THEME = "amelia.css" # amelia theme #APP_THEME = "cosmo.css" # cosmo theme APP_THEME = "cyborg.css" # cyborg theme #APP_THEME = "flatly.css" # flatly theme
To run the skeleton app, use the below-given command on the terminal.
flask run
Flask Hello World
To create your first program in the flaskTutorialApp, open file views.py under the app directory and add the following code. Look for import statements given in the file. Add these statements if not already present.
from flask_appbuilder import BaseView, expose from app import appbuilder class HelloWorld(BaseView): """ This first view of the tutorial """ route_base = "/hello" @expose("/") def hello(self): return "Hello, World! from Software Testing Help" # at the end of the file appbuilder.add_view_no_menu(HelloWorld())
Save the file after adding the above source code. Go to the project’s root directory and use the below command to run the Flask’s development server.
flask run
Now navigate to http://localhost:5000/hello/ to see the output in the browser.
Debugging
Currently, the development server is not running in the Debug mode. Without debugging mode, it is difficult to find the errors in the source code of the Flask Application.
Debug Mode in Flask results in the following:
- Debug mode activates Automatic reloader. It means that we need not restart the development server after we make changes in the source code of the application.
- Debug mode activates the Python debugger. We can inspect the values of variables during the Exception.
- Debug mode enables Flask application debugging. We can check the values of various variables in debugging sessions.
Stop the development server if it is already running. You can use CTRL + C or Keyboard interrupt to do the same.
Use the following code to enable the debug mode and run the development server temporarily.
FLASK_ENV=development flask run
Search the console for Debugger PIN and make a note of it.
Now let’s change the above written HelloWorld view with the following lines of the code snippet. Notice that we have introduced a custom exception.
@expose("/") def hello(self): raise Exception("A custom exception to learn DEBUG Mode") return "Hello, World! from Software Testing Help"
Navigate to http://localhost:5000/hello/, and you will see that the application has raised an exception. The browser displays the stack trace, as shown below.
Furthermore, look at the console where the development server is running. You will find that this time, the changes in the views.py are automatically detected, and the debug server restarts by itself. Now we need not manually restart it.
The console will have lines, as shown below. We need to note down the Debug PIN for later.
* Detected change in '/work/sth/flaskTutorialApp/app/views.py', reloading 2020-06-02 14:59:49,354:INFO:werkzeug: * Detected change in '/work/sth/flaskTutorialApp/app/views.py', reloading * Restarting with stat 2020-06-02 14:59:49,592:INFO:werkzeug: * Restarting with stat * Debugger is active! * Debugger PIN: 150-849-897
Now check the stack trace in the browser and go to the last line. Click on it to expand its view and click on the CLI icon to open the shell in interactive mode.
Once you open it, You will see that the browser will show a prompt for Debug PIN. Give the Debug PIN and click on OK.
Once we proceed ahead after giving the Debug PIN, we can access the interactive shell.
We access the shell from within the browser and can inspect the values of variables to find the cause of the Exception and handle the error in a better way. Please look at one of the examples shown in the image below.
Now change the code in view.py, as shown below. Note that we have commented on the line that had the raised Exception.
@expose("/") def hello(self): # raise Exception("A custom exception to learn DEBUG Mode") return "Hello, World! from Software Testing Help"
Testing The Flask Application
Now let’s write our first test for the Flask application that we are developing. First, install the PyTest. PyTest is a testing framework. It helps us to write better code.
Moreover, just because we can write unit tests while developing our applications, it is possible to follow the TDD approach. TDD stands for Test-Driven Development. In our subsequent tutorials of this series, we shall always write tests first and develop our views or models.
Install PyTest
pip install pytest
Now create a directory called tests inside the app directory and in that create a file called test_hello.py. Let’s write our first unit test to test our view.
Copy the following code snippet and paste it into test_hello.py.
#!/usr/bin/env python from app import appbuilder import pytest @pytest.fixture def client(): """ A pytest fixture for test client """ appbuilder.app.config["TESTING"] = True with appbuilder.app.test_client() as client: yield client def test_hello(client): """ A test method to test view hello """ resp = client.get("/hello", follow_redirects=True) assert 200 == resp.status_code
Use the below pytest command to run the tests. PyTest automatically collects the Tests and displays the results on the standard output.
Create A GitHub Workflow
We use Git Actions to create a CI/CD workflow for our sample application. Follow the below-mentioned steps for your project.
Step 1: Navigate to the repository page on GitHub. Click on Git Actions.
Step 2: Scroll down on the page and find an existing workflow template for a Python package.
Step 3: Setup the Python package Workflow.
Step 4: Once the python-package.yml workflow configuration opens, update it based on the given yaml additional tag values.
name: flaskTutorialApp jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: [3.7, 3.8] mongodb-version: [4.2] steps: - name: Start MongoDB uses: supercharge/mongodb-github-action@1.3.0 with: mongodb-version: ${{ matrix.mongodb-version }} # other values
We want to test our Flask application on the latest Ubuntu Linux distribution. In addition to the OS, we want to run our tests only using Python 3.7 and Python 3.8.
Step 5: Commit the python-package.yml with the updated values.
Step 6: The commit in the previous page takes us to the GitActions jobs.
Step 7: [Optional]
On the Github Jobs page for the sample tutorial app, we can create a badge and place it on the README.md file for displaying the build status.
Now, whenever the changes are committed to the master branch, Git Workflow, as written in python-package.yml will be followed and run on Git Actions.
Conclusion
In this tutorial, we have covered all the base concepts from prerequisites to setting up CI/CD workflow for a web application developed using Flask – A Python-based web development framework.
This tutorial covers all necessary steps such as installing Python, downloading & installing Flask, working with Flask-Appbuilder, testing with PyTest, etc. to get started with web development using Python. The web development community usually compares Flask with another popular Python web development framework called Django.
We will explain these differences and will also compare these frameworks in one of the tutorials in this series.