If you’re a web developer using Python as your server-side programming language of choice, you have a number of web frameworks to choose from. One of the most notable is Flask.
Flask is a micro-framework developed in Python that provides only the essential components - things like routing, request handling, sessions, and so on. It provides you with libraries, tools, and modules to develop web applications like a blog, wiki, or even a commercial website. It’s considered “beginner friendly” because it doesn’t have boilerplate code or dependencies which can distract from the primary function of an application.
Flask is used for the backend, but it makes use of a templating language called Jinja2 which is used to create HTML, XML or other markup formats that are returned to the user via an HTTP request. More on that in a bit.
The purpose of this post is to give you a quick Python Flask tutorial on creating your first Flask application. And if you have a little Python know-how, you can quickly hit the ground running and start creating web apps in no time. If you’d like to get started on your first project in Flask, you can visit here.
(If you’re looking to learn Python from scratch, you can check out our free course here.)
So, here’s what we’ll look at today:
Let’s dive in!
Some features which make Flask an ideal framework for web application development are:
Micro-frameworks are the opposite of full-stack frameworks, which also offer additional modules for features such as authentication, database ORM, input validation and sanitization, etc.
Flask is known as a micro-framework because it is lightweight and only provides components that are essential, such as routing, request handling, sessions, and so on. For the other functionalities such as data handling, the developer can write a custom module or use an extension. This approach avoids unnecessary boilerplate code, which is not even being used.
You might have heard comments such as “Flask is 100% WSGI compliant” or, “flask uses Jinja as a template language.” But what exactly does this mean? What are WSGI and Jinja2? Let’s learn what these terms mean, and their significance concerning Flask.
The Web Server Gateway Interface, or more commonly known as WSGI, is a standard that describes the specifications concerning the communication between a web server and a client application. The details of these specifications are present in PEP333. Here are some benefits of WSGI:
Jinja is a template language used in Python. But, you might ask, what exactly is a template language?
Templates are the front-end, which the user sees. In the case of a website, the templates are the HTML pages. A template language is one that we can use inside HTML so that the content on the HTML page becomes dynamic.
Let’s move on to creating your first Flask application.
The simplest Flask application can be made using only one script! Let us call this file app.py. We will break down the program into steps and discuss each one.
For this application, we only need the Flask module from the flask package. So let’s import that first.
from flask import Flask
We need to make an object with the imported Flask module. This object will be our WSGI application called
app. As discussed before, the WSGI aspect of the application is taken care of by the Flask module.
app = Flask(__name__)
To run our application, we need to call the
run() function of our application object.
if __name__ == "__main__": app.run()
run() function has some optional parameters. For complete documentation, refer here.
Before we run the application, we need to tell the application to show something as output in the browser window. Thus, we create a function called
hello() which returns the string “Hello World!”. The output returned from this function will be shown in the browser.
def hello(): return "Hello World!";
Finally, we need to tell the Flask app when to call the view function
hello(). For this purpose, we will create a URL route. A URL route is associated with each view function. This association is created by using the
route() decorator before each view function.
@app.route("/") def hello(): return "Hello World!";
The following program shows the complete implementation of a “Hello World” application in Flask!
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!"; if __name__ == "__main__": app.run(debug = True, host = "0.0.0.0", port = 3000)
The homepage of a website can usually be found at the URL
hostname followed by
/index or something self-explanatory.
These kinds of URLs enable the users to remember the URL and access it easily. It would be unexpected if the homepage were at a random URL such as
Flask allows us to use the
route() decorator to bind a meaningful URL to each view function we create.
In the discussion of the MTV (Model-Template-View) architecture, we learned what a view is. In Flask, we create a function that acts as the view. Recall from the Hello World example, we created a function called
hello. This function acted as a view. Then, we bonded it with a route.
@app.route("/") def hello(): return "Hello World!";
The route decorator takes the following parameters:
rule: The rule represents the URL rule which is passed as a string to the decorator.
endpoint(not needed): The endpoint is the name of the view function which is bound to the URL route. Flask assumes this parameter itself, and the developer does not need to specify it.
options(optional): The options are an optional parameter. We will discuss it in more detail later.
In static routing, we specify a constant URL string as rule to the
route() decorator. For example in the mini-application given below, we have specified two static routes having URLs
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def home(): return "Welcome to the HomePage!" @app.route("/educative") def learn(): return "Happy Learning at Educative!" if __name__ == "__main__": app.run(debug=True, host="0.0.0.0", port=3000)
This view function corresponds to the route
"/". When you open the URL or check the “Output” tab, this view will be called. The
"/" is always the default route of any web application.
For example, when we go to educative.io the
host = “educative.io” and
route = “/”.
This view function corresponds to the route
"/educative". When you open the URL and append
"/educative", this view will be called.
In the previous sections, we implemented our first Flask application (i.e. Hello World), learned how to create static URL routes, and how to bind them to views. Using this information, we will now start building a real-world application.
The application we’ll be building is an animal rescue website called “Paws Rescue Center”. Let’s start to create an application with a Home page and About page.
In this challenge, we will implement the views for the ‘home’ and ‘about’ pages of the application.
"Paws Rescue Center 🐾".
"We are a non-profit organization working as an animal rescue. We aim to help you connect with the purrfect furbaby for you! The animals you find on our website are rescued and rehabilitated animals. Our mission is to promote the ideology "adopt, don't Shop"! ".
Home page expected output
About page expected output
Here’s the complete implementation for the start of this project:
"""Flask Application for Paws Rescue Center.""" from flask import Flask app = Flask(__name__) @app.route("/") def homepage(): """View function for Home Page.""" return "Paws Rescue Center 🐾" @app.route("/about") def about(): """View function for About Page.""" return """We are a non-profit organization working as an animal rescue center. We aim to help you connect with the purrfect furbaby for you! The animals you find at our website are rescue animals which have been rehabilitated. Our mission is to promote the ideology of "Adopt, don't Shop"! """ if __name__ == "__main__": app.run(debug=True, host="0.0.0.0", port=3000)
This challenge was meant to get us started with development with the Flask framework. Let’s break down the solution and analyze it.
First, let us take a look at the solution for the home page.
We want the home page to be the first landing page of the website, therefore, using the route
"/" makes the most sense, as shown in line #5.
"Paws Rescue Center 🐾", was provided in the challenge as the required output. All we had to do was to return this string in the view function. This can be found on line #8 in the solution shown above.
Next, for the about page, the following features were implemented.
The most obvious and user-friendly URL route for the about page is
"/about" (referring to line #10 in the solution).
The output string provided in the problem statement is returned in lines #13-16.
There is still a lot to do to make this a finished product, but here’s what it looks like when you’re all finished. If you’d like to continue working on this project with a step-by-step guide you can visit here.
Congrats! You’ve learned how to create your first Flask application and started your first project. There is still much to learn though like static and dynamic templates, form handling, connecting to a database with SQLAlchemy, and the different operations you can perform on models (i.e. insertion, retrieval, etc.).
If you have any interest in developing web apps with Flask, I highly recommend this project-based course, Flask: Developing Web Applications in Python. You’ll explore everything that’s mentioned above (static/dynamic templates, form handling, etc.) and the rewarding part is that you get to work on and finish the project you just started, which you can then add to your portfolio.
Why continue to learn the Flask framework? It’s a very valuable skill if you’re hoping to pursue a full stack developer position. Full stack developers are in high demand because of their ability to contribute across the board. This is a great opportunity to further explore both sides of development, which in turn can make you a more richly compensated developer.
Join a community of 270,000 monthly readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.