Capstone: A Flask Guestbook
The guestbook is the capstone app. It shows messages, takes new ones, and ties the course together.
Make the app
This line imports the guestbook tools together. The list below holds the messages.
from flask import Flask, request, redirect, url_for, render_template_string
app = Flask(__name__)
messages = []Show the guestbook
The view renders the messages with a loop, then a form for new ones.
@app.route("/")
def guestbook():
return render_template_string('<h1>Guestbook</h1>{% for m in messages %}<p>{{ m }}</p>{% endfor %}<form action="/sign" method="post"><input name="message"><button>Sign</button></form>', messages=messages)Sign the guestbook
The POST route saves a non-empty message and redirects to the guestbook page.
@app.route("/sign", methods=["POST"])
def sign():
message = request.form.get("message", "")
if message != "":
messages.append(message)
return redirect(url_for("guestbook"))Sign twice, then read the book
The test client signs twice and prints the finished guestbook page with both messages.
client = app.test_client()
client.post("/sign", data={"message": "Hello!"}, follow_redirects=True)
client.post("/sign", data={"message": "Great site"}, follow_redirects=True)
print(client.get("/").data.decode())Example
from flask import Flask, request, redirect, url_for, render_template_string
app = Flask(__name__)
messages = []
@app.route("/")
def guestbook():
return render_template_string('<h1>Guestbook</h1>{% for m in messages %}<p>{{ m }}</p>{% endfor %}<form action="/sign" method="post"><input name="message"><button>Sign</button></form>', messages=messages)
@app.route("/sign", methods=["POST"])
def sign():
message = request.form.get("message", "")
if message != "":
messages.append(message)
return redirect(url_for("guestbook"))
client = app.test_client()
client.post("/sign", data={"message": "Hello!"}, follow_redirects=True)
client.post("/sign", data={"message": "Great site"}, follow_redirects=True)
print(client.get("/").data.decode())Key points
- GET / shows the messages and the form.
- POST /sign saves a message and redirects.
- The messages live in a list while the app runs.
- The template loops over the messages.
In this example, the guestbook page renders the messages with a loop and a form for new ones. The /sign route saves a non-empty message and redirects to the page. The test client signs twice, and the print shows the finished page with both messages.
Note
A real guestbook would save messages in a file or a database.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens after POST /sign saves a message?