25% developed

Making Websites with Flask/Printable version

From Wikibooks, open books for an open world
Jump to navigation Jump to search


Making Websites with Flask

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Making_Websites_with_Flask

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.


Introduction

What is Flask?[edit | edit source]

Flask is a microframework for making websites with Python. It's super easy to get started. However, Flask does not have features like authentication or database connecting built-in, unlike other web frameworks. However, there are extensions for those things.

Flask is a backend web framework which means that it handles everything behind the scenes. This means that Flask handles the user requests in the server.

Flask is used by LinkedIn and Pinterest.

History[edit | edit source]

Flask was created by Austrian programmer Armin Ronacher in 2010.

Prequesites[edit | edit source]

  • Experience with Python 3
  • Experience with HTML




Getting Started

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



Routing

What is Routing?[edit | edit source]

Routing basically means returning something to the user when they visit a specific URL on the site, which is called a route. In the Getting Started tutorial, we had two routes: the root route, /, and /hello.

Route Variables[edit | edit source]

Variable Rules[edit | edit source]

Trailing Slash[edit | edit source]

URL Building[edit | edit source]



Templating

What is templating?[edit | edit source]

When we are making Flask apps, we often want to return an HTML file, not just a string of HTML. Using templating, we can do this, along with many more advanced things like variables, loops, base templates, and more.

Making a Template File[edit | edit source]

To make a template file, we make an HTML file in a folder called templates. For example, let's make called our HTML file index.html and put the following in it:
<!DOCTYPE html>
<html>
    <head>
        <title>My Website</title>
    </head>
    <body>
        <h1>Welcome to my Website!</h1>
        <p>Hello world!</p>
    </body>
</html>

Displaying Templates[edit | edit source]

To display a template, we use the render_template() function. To use it, we first of all need to import it from the Flask module:
from flask import render_template
Then, we use the render_template() function when we are returning our functions. We pass in the name of the template HTML file into the render_template() function. So, something like the following:
@app.route("/template")
def template_page():
    return render_template("index.html")

Using Python Variables in Templates[edit | edit source]

For and While Loops[edit | edit source]

Creating a Base Template[edit | edit source]

Changing the Templates Folder[edit | edit source]