Jump to content

Making Websites with Flask/Getting Started

100% developed
From Wikibooks, open books for an open world

Installation

[edit | edit source]

Flask is a Python library, so you first of course need Python installed. Then, you can use the pip package manager to install Flask:

pip install flask

To make sure you installed Flask correctly, run the following Python script:

import flask

If it runs without any errors, you have successfully installed Flask!

Hello World!

[edit | edit source]

In programming, it is a tradition to make a program that displays "Hello World!". So, we will make a website that returns "Hello World!" when we visit it.

In your code editor, write the following code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello World!"

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

Now, save the Python code and run it as you would any other Python program. Then, when you visit localhost:7070, you should "Hello World!".

Code Breakdown

[edit | edit source]

Now, let's break down the code that we just wrote line by line.

First of all, we need to import the things we need from the Flask module (line 1):

from flask import Flask

Then, we need to create an instance of the Flask object, which represents our web app (line 3):

app = Flask(__name__)

Then, we create a decorator. Decorators are functions that modify the next function. In this case, the decorator shows the user whatever is returned by the next function when the user visits the root page (line 5):

@app.route("/")

Then, we actually create the function which will be modified by the decorator and make it return "Hello World!" (lines 5 and 6):

def hello_world():
    return "Hello World!"

We could also make the function return some HTML:

def hello_world():
    return "<h1>Hello World!</h1>"

Then, we run the Flask object at port 7070 (lines 9 and 10):

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

Adding More Routes

[edit | edit source]

Of course, there's nothing stopping us from having more routes. For example, let's add the following code:

@app.route("/about")
def about():
    return "<h1>This is my first Flask website!</h1>"

For the sake of completeness, here's the entire code with the new code block:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello World!"

@app.route("/about")
def about():
    return "<h1>This is my first Flask website!</h1>"

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

Now, whenever we visit localhost:7070/about, we see "This is my first Flask website" in headings (notice that we added HTML tags to the output of the function).