Birthdays Practice Problem Set Solution
“Server-Side” Python app.py
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///birthdays.db")
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
# TODO: Add the user's entry into the database
nameVar = request.form.get("name")
anything = request.form.get("month")
day = request.form.get("day")
# check that all our entries are valid before sending the query
if nameVar and anything and day:
# SQL insert into query
db.execute("INSERT INTO birthdays (name, day, month) VALUES (?, ?, ?)", nameVar, day, anything)
return redirect("/")
else: # this must be get, since only two "methods" have been defined for this route
# TODO: Display the entries in the database on index.html
# SQL select query
liDct = db.execute("SELECT * FROM birthdays")
# we can still print to the terminal! -> note we ALWAYS return a list of dictioanries from SELECT
print(liDct)
# render the template, passing in our list of dictionaries data
return render_template("index.html", data = liDct)
“Client-Side” HTML index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
<link href="/static/styles.css" rel="stylesheet">
<title>Birthdays</title>
</head>
<body>
<div class="header">
<h1>Birthdays</h1>
</div>
<div class="container">
<div class="section">
<h2>Add a Birthday</h2>
<!-- TODO: Create a form for users to submit a name, a month, and a day -->
<form action="/" method="post">
<input autocomplete="off" autofocus name="name" placeholder="Name" type="text">
<input autocomplete="off" name="day" placeholder="Day" type="number" min="1" max="12">
<input autocomplete="off" name="month" placeholder="Month" type="number">
<button type="submit">Add Birthday</button>
</form>
</div>
<div class="section">
<h2>All Birthdays</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Birthday</th>
</tr>
</thead>
<tbody>
<!-- TODO: Loop through the database entries to display them in this table -->
{% for dct in data %}
<tr>
<td> {{ dct["name"] }} </td>
<td> {{ dct.month }}/{{ dct.day }} </td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</body>
</html>