Full Stack Python Flask tutorial: Creating your first Flask Application

cameronwilson

Cameron Wilson

Posted on January 11, 2020

Full Stack Python Flask tutorial: Creating your first Flask Application

Originally posted on Educative.io

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.

So, here’s what we’ll look at today:

  • Getting to know the Flask framework
  • Hello World - your first Flask application
  • URL Routes and Views
  • Taking it a step further: Beginning your first project

Let’s dive in!

Getting to know the Flask framework

Features of Flask

Some features which make Flask an ideal framework for web application development are:
1) Flask provides a development server and a debugger.
2) It uses Jinja2 templates. (more on this later)
3) It is compliant with WSGI 1.0. (more on this later)
4) It provides integrated support for unit testing.
5) Many extensions are available for Flask, which can be used to enhance its functionalities.

What is a micro-framework?

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.

Why is Flask called a micro-framework?

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.

Key aspects of Flask: WSGI and Jinja2

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.

WSGI - Web Server Gateway Interface

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:

  • Flexibility with the components of the application.
  • Interoperability within different Python frameworks.
  • Scalability of the application with an increase in users.
  • Efficiency in terms of speed of development.

Jinja2 - A templating language

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.

Hello World - 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.

Step 1: Importing modules

For this application, we only need the Flask module from the flask package. So let’s import that first.

from flask import Flask

Step 2: Creating a Flask object

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__)

Step 3: Run the application in main

To run our application, we need to call the run() function of our application object.

if __name__ == "__main__":
    app.run()

The run() function has some optional parameters. For complete documentation, refer here.

Step 4: Create a view function

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!"; 

Step 5: Assign a URL route

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!"; 

Complete implementation

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)

Wait.. what are views, routes, and hosts?

URL routes and views

The homepage of a website can usually be found at the URL hostname followed by /, /home, /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 /39283@&3911 or /more_eggs. Flask allows us to use the route() decorator to bind a meaningful URL to each view function we create.

What is a view function?

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

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.

Static routing

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 / and /educative respectively.

Example:

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)

Explanation

home() view

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 = “/”.

learn() view

This view function corresponds to the route "/educative". When you open the URL and append "/educative", this view will be called.

For example, when we go to educative.io/explore, the host = “educative.io” and route = “/explore”.

Ready to get a project started? Here's your task

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.

Problem statement

In this challenge, we will implement the views for the ‘home’ and ‘about’ pages of the application.
1) The URL routes for both views should be user-friendly.
2) The home page should output the string: "Paws Rescue Center 🐾".
3) The about function should output the following line: "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

Alt Text

About page expected output

Alt Text

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)

Explanation

This challenge was meant to get us started with development with the Flask framework. Let’s break down the solution and analyze it.

Home page

First, let us take a look at the solution for the home page.

URL route

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.

Output

The string, "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.

About page

Next, for the about page, the following features were implemented.

URL route

The most obvious and user-friendly URL route for the about page is "/about" (referring to line #10 in the solution).

Output

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.

Alt Text

What’s next?

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.

💖 💪 🙅 🚩
cameronwilson
Cameron Wilson

Posted on January 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related