Getting started

Installation

We'll need just a few things to get started with building Flask applications. Crucially we'll need Python 3, a terminal, and a text editor. Many systems come built in with Python 3. If you run into issues, Appendix A has some common issues and resolutions, including installation instructions for Windows.

tip

If you need a text editor, we use Visual Studio Code. Like Flask it's free, and powerful out of the box but can be customized for power users.

Let's start by creating a folder for our Flask projects. This is the folder where we will place each of the example applications we build throughout this book.

mkdir fullstack-flask
cd fullstack-flask

Then let's create a folder for our first Flask application.

mkdir 'first-flask-app'
cd 'first-flask-app'

Now that we have Python 3, we'll want to install Flask. Flask is packaged as a library that we can install using pip, a package manager for Python. Before we do that, we should set up an environment within our project folder where we can specify exactly which version of Python and libraries we would like to use. Python 3 comes built in with a tool to create "virtual environments" called virtualenv. What this will do is reference a version of Python and libraries installed within the specific project folder. Using virtualenv makes it easier to manage multiple projects that may have conflicting dependencies.

When we work without virtual environments and have multiple projects, we can quickly run into conflicts between versions of underlying libraries and Python versions.

Projects will use the system default version of Python and libraries
Projects will use the system default version of Python and libraries

When we use virtual environments, we can isolate the version of Python and which version the project uses.

Virtual environment allows specifying versions on a project level
Virtual environment allows specifying versions on a project level

In order to make virtual environments work, we need to "activate" each one before running our application so that our terminal session will use the correct version before each

Within the first-flask-app folder, we are going to want to create a folder for the virtual environment which we can call env. We'll only need to do this once. By running this command, we create a folder and set up a virtualenv tied to the version of Python we are using. The -m venv flag tells Python to run the built in virtualenv module.

python3 -m venv env

Now that the environment is configured, we'll need to make sure our terminal session uses virtualenv's configuration for Python instead of the defaults. To do so, we run a script to activate the virtual environment.

source env/bin/activate

This will prefix your terminal prompt with (env) to let you know that it has been activated. Now we can install Flask.

pip install flask

Hello World: Dice

Our goal for this part is to have a page that loads in our browser that displays a random number every time we load the page.

In order to have a page that displays a random number, we're going to have write some logic that we can later tell Flask to serve to the browser. Let's start by writing a function that returns the result of a dice roll. We're going to need to create a file to write the function in; we can use the same file to run the Flask web server as well. We'll call this file hello_world.py.

touch hello_world.py  # creates a file

Now open hello_world.py in our text editor. In this book, we'll be using VS Code, but you can use whatever editor you like. In VS Code, you can open the file (or folder) directly from the terminal

code hello_world.py
first-flask-app/hello_world.py
from random import randint

def roll_dice():
    random_number = randint(1, 6)
    return "The dice rolled: {}".format(random_number)

The code above has a function that returns a the result of a dice roll. We use the built in random.randint function to get a random integer between 1 and 6.

Once we've added this in our server.py file (and saved the file), we can make sure it works by firing up an interactive interpreter and calling the roll_dice() function.

$ python3 -i hello_world.py
>>> roll_dice()
"The dice rolled 4"

Now that we have a function, we'll want to import Flask and tell Flask to use the roll_dice function when serving web requests. Once we've imported Flask, we need to initialize it by passing in the name for our web application. The convention for the name of the Flask server is to use the name of the Python module that the server is defined in. Python provides that name in a read-only variable called __name__.

first-flask-app/hello_world.py
from flask import Flask
app = Flask(__name__)

The first line imports the Flask class from the flask library. The second line is creating an instance of the Flask class for us to define our own web application.

Now we'll want to tell Flask to use our roll_dice function when someone requests the home page of the server. All we have to do for that is to add a line above the roll_dice function with a Python decorator to tell Flask to use the function on the root of the web application (/)

first-flask-app/hello_world.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def roll_dice():
    random_number = randint(1, 6)
    return "The dice rolled: {}".format(random_number)

That's all of the changes we need to make to make our Python function into a web application. The simplicity of Flask makes it easy to get started without having to learn a lot of Flask specific knowledge.

Testing it out

In our terminal, we can start a local server to run this code and see what happens. When we installed Flask, it came bundled with a command line interface as well. One off the commands is flask run which spins up a development server so that we can run the web application from our own computer. We will need to tell Flask where our application is in the form of an environment variable. We could set it for the duration of our session by setting those environment variables in our shell session.

export FLASK_APP=server FLASK_ENV=development

Another way we could specify these is to prefix the command we run with FLASK_ENV=development FLASK_APP=server. In our examples, we'll include the full command for clarity.

FLASK_ENV=development FLASK_APP=hello_world flask run

When set to development, the FLASK_ENV environment variable will display detailed errors as well reload the application if we change the code so that we don't need to restart the server manually.

In our terminal (with our virtualenv activated), we can now run the server. You should see something similar to below.

$ FLASK_ENV=development FLASK_APP=hello_world flask run
 * Serving Flask app "hello_world"
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
note

Make sure you have activated the virtual environment and run pip install flask within it.

If you have not configured your virtual environment, you might run into issues where the flask command is not found

Common issues can involve a syntax error. To validate that your Python file is syntactically valid, you can run python server.py just to see if the program runs.

If you were able to get the development server running, you can now open a web browser (like Google Chrome or Firefox) and navigate to http://127.0.0.1:5000. The 127.0.0.1 is an IP address that refers to your computer (also referred to as localhost) and the 5000 references a specific port number that Flask is using.

You should see a webpage that shows the output of the function. The dice rolled: 6

Our Flask Dice Application
Our Flask Dice Application
note

Want to make your application more interesting? If someone rolls a five, try making the website change the text to "Lucky roll! You got a five!"

Start a new discussion. All notification go to the author.