Making Websites with Flask/Printable version
This is the print version of Making Websites with Flask You won't see this message or any elements not part of the book's content when you print or preview this page. |
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
Introduction
What is Flask?
editFlask 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, it is designed to make programming these easy.
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
editFlask was created by Austrian programmer Armin Ronacher in 2010.
Prequesites
edit- Experience with Python 3
- Experience with HTML
Getting Started
Installation
editFlask 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!
editIn 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
editNow, 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
editOf 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?
editRouting 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
.
URL Building with Route Variables
editURL building is the practice of having dynamically served URLs, that are not built in. An example of this would be if you had a /user
route, but the URL was formatted like /user/randomUser
. In a Flask app without route variables, you would manually need to add each user with @app.route
many times, but with Route Variables you can just say @app.route('/user/<name>')
, and you can show the account page.
Templating
What is templating?
editWhen 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
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
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")
Inline Code Storing
editAnother way you can serve HTML code is by serving it inline. Here is a example:
from flask import *
app = Flask(__name__)
@app.route('/')
def inline_example();
return """
<!DOCTYPE html><html>
<head>
<title>My Inline Code Example</title>
</head>
<body>
<h1>You did it</h1>
Good Job!
</body>
</html>
"""
if __name__ == "__main__":
app.run(debug=true)
In this example, instead of the HTML being loaded from an external file, it is being directly given to the user.
Test it out
editOn your Python editor, run the program. Then open a browser. Navigate to http://127.0.0.1:5000/ and you should see a web page congratulating you. If you don't, check the console to debug.
Creating a web app
Now that you have learned the basics of Flask website development, it is time for the final project. We will be making a web application in which someone can someone can upload their name, age and favourite food, and every other user can view this information.
Creating the homepage
editWe will now create the homepage for the website so that when someone connects, they will know what this is.
Here is the code:
from flask import *
app = Flask(__name__)
#This creates the application object for the site
@app.route('/')
def home():
#You can modify this HTML how you see fit
return """
<!DOCTYPE html>
<html>
<head>
<title>Learn about other users</title>
</head>
<body>
<h1>Welcome to my Web App!</h1>
<a href="/signup">Click here to create a account!</a>
<p style="font-family: sans-serif;">This is a cool website to learn about fellow users.</p>
</body>
</html>
"""
if __name__ == "__main__":
app.run(debug=True)
As you can see, it links to a sign up page, that does not exist yet. We will now address this issue.
Making the sign up page
editFor someone to use your website, they must create an account. But first, we must create a list of all accounts. We will structure it like this: accounts = [{"name": "John Doe", "age": 20, "food": "pizza"}]
. In the next chapter we will code this page, and more.