Introduction to Flask#

Author: Mike Wood

Learning Objectives: By the end of this notebook, you should be able to:

  1. Write a simple flask script to create a web page

  2. Set Flask environment variables and host a local web serve

What is Flask?#

Flask is a Python-based web framework designed to developing web applications. It is lightweight but has tools for building web applications such as templating and requests. We will take a look at some of these features in the following pages.

Installing Flask#

To install flask in your conda environment, you can use the standard conda installation:

conda install flask

A First Example#

Let’s take a look at first example of a Flask application. The following application will generate a simple page with a little bit of text, akin to a “Hello World” application:

# import the Flask class from the flask module
from flask import Flask

# create a Flask object called app
app = Flask(__name__)

# define a route to the home page
# create a hey_there function
@app.route("/")
def hey_there():
    return "What's Up"

As we can see in the code block above, we first make an app object with the Flask class:

app = Flask(__name__)

Next, we add pages to our app with a decorator for the route and a function for the functionality of the page:

@app.route("/")
def hey_there():
    return "What's Up"

In this case, the string “What’s Up” will just be added to the page.

To run this application, we need to set up our application for use in a development environment. In a command line (with your conda environment activated), run the following lines:

export FLASK_APP=hey_there.py
set FLASK_APP=hey_there.py
export FLASK_ENV=development
set FLASK_DEBUG=True

If you are on Windows and using Powershell, you can set environment variables as follows:

$env:FLASK_APP = "hey_there.py"

As you can see, the hey_there.py script is explicitly linked in the environmental variables.

Once you’ve set up these lines, the app is ready to run! From the command line, run

flask run

This will set up a local IP address like 127.0.0.1:5000 or something similar. You can navigate to the page in your favorite web browser to view your work. Your page will look like the example page HERE

The steps above reflect the basic structure of a simple Flask app. Now that we’ve got the basic structure down, let’s add some more functionality to our app.