Maker Pro
Custom

An Introduction to the Python Flask Framework

May 22, 2019 by Robin Hartley
Share
banner

Get started with Flask, a Python-based framework for web development, and learn how you can use it in your IoT projects!

If you’ve played around with Python and you’re confident writing code, then you may be ready to step it up and try developing your own Python-powered website!

While Python is well-known for its capabilities in data analysis and machine learning, it is also used to run some of the largest websites on the internet, including Reddit, Netflix, Pinterest, and Instagram.

Choosing a Framework: Django or Flask?

If you want to try out some Python web development, you first have to choose between two frameworks: Flask or Django. They both do the same thing – they convert your Python code into a fully-functioning web server.

Flask is a minimalist version in which everything is an optional extra you can choose, whereas Django comes with everything already “plugged in” and has pre-defined libraries, techniques, and technologies that you use out-of-the-box.

Flask is good for beginners and for quickly building small/medium applications. Django is arguably better for large enterprise applications, but also requires a deeper understanding.

For this tutorial, we’ll start with Flask, but you can always hop over to Django in the future once you’re comfortable with the basics.

Installing Flask

As with most libraries in Python, installation is a dream – just install it with pip:

$ pip install Flask

That’s it! Onto the next section.

Client and Server

Before we begin developing our first Flask web app, we need to clear up the roles of the client and the server. The client is a web browser, like Google Chrome or Firefox. When you type in a web address and press enter, you’ll send a request to a server that will “serve” the website you want.

The server will respond to your request with the website (in the form of HTML, CSS, and JavaScript) and then render this request in your web browser. HTML defines the structure of the website, CSS gives it styling, and JavaScript is the logic that executes in your browser.

Flask is a server-side framework or “back-end” as it’s often called. You program the bit of code that receives a request, builds a web page, and then responds with the necessary HTML (and optional CSS and JavaScript).

The discipline of client-side development or “front-end” is concerned with how the website behaves in the browser after it is received from the server. We will not focus on this as client-side development is pretty much only done in JavaScript.

Your First Flask Web App

Let’s begin with the time-honored tradition of a “Hello World” application. This example is a slightly modified version of the Hello World app in the Flask documentation.

from flask import Flask     # Import Flask
app = Flask(__name__)       # Create a Flask "app" instance


@app.route("/")             # Instructs that the default url of http://127.0.0.1:5000/ should trigger this code
@app.route("/index")        # Instructs that the url of http://127.0.0.1:5000/index should also trigger this code
def index():
    return "<h1>Hello World!</h1>"          # The HTML to return to the browser


if __name__ == '__main__':                  # Startup stuff
    app.run(host='127.0.0.1', port=5000)    # Specify the port and url

Run the code and then go to Google Chrome (or your browser of choice) and type in “http://127.0.0.1:5000/”, without the quotes. You should see a delightful “Hello World” appear, welcoming you to the world of web development.

A Scalable Structure for Flask Web Apps

While having all of the code in a single file is a quick and exciting introduction to Flask, you will probably want to split your code into separate files to make it more manageable.

To help you in this, I’ve created a simple structure you can use for your Flask applications. Head over to GitHub to grab the source code for yourself.

This structure has a “start.py” script that you run to fire-up your webserver. All of the Python code is inside a folder called “code”. This folder is where your “routes.py” file lives. It contains the definitions for requesting web URLs and how your app responds when they are.

If you have any Python logic such as calculating stats or machine learning models, then these should also go inside the “code” folder.

The “templates” folder houses the HTML files that will be returned by the server. They’re called templates because you can optionally insert values to change the text and graphics at runtime.

The “static” folder contains code like CSS and Javascript that does not change at runtime.

Setting Up Deployment

With what we’ve discussed so far, you’ll be able to create a web app that runs on your computer, but if you try and access your website from another computer, you’ll run into difficulties. This is the topic of deployment.

First, we need to adjust the port on which your website presents itself. We want to set the host to “host=0.0.0.0” and the port to “port=80”. Setting the host and port makes your website visible on the IP address of your host computer.

For example, if you run your Flask web app on a Raspberry Pi with an IP address of 192.168.1.10, then you can navigate to that IP address in the web browser of a separate computer, and you’ll see your web page served up for you. This is a great foundation for IoT projects and live sensor dashboards.

We define that “port=80” as this is the default port for communication over the HTTP protocol. When you request a URL in your browser over HTTP, it knows to go to port 80, so you don’t have to state it explicitly in the web address.

For all of this to work, you’ll have to be on the same network as the computer running your web server, and you’ll need to make sure that the firewall on your host computer (if you have one) is opened up to requests on port 80.

Next Steps and Going Further

If you want to take a deep-dive into Flask web development, then I strongly recommend the Flask Mega Tutorial by Miguel Grinberg. It’s very detailed and is an invaluable source for learning Flask.

Author

Avatar
Robin Hartley

I'm a software developer and engineer based in Sheffield, UK. I also created the keystroke automation software: http://numpadsuperpowers.com

Related Content

Comments


You May Also Like