This is CS50 �Week 9
View
Controller
View
Controller
View
Model
birthdays/
static/
styles.css
templates/
index.html
app.py
birthdays.db
Routes
https://example.com/
https://example.com/add
@app.route("/")
def index():
# Return index page
@app.route("/")
def index():
return render_template("index.html")
flask run
Forms
POST
GET
POST vs GET Request Methods
A user goes to a website and lands on the /login page.
A user goes to a website and lands on the /login page.
GET
A user enters their username and password and clicks Log In.
A user enters their username and password and clicks Log In.
POST
A user submits a birthday.
A user submits a birthday.
POST
Form element
<form action="/" method="post">� ...�</form>
Route to request
Request method
Elements of forms
<input name="friend" type="text">
<input name="month" type="number">
<button type="submit">...</button>
Elements of forms
<input name="friend" type="text">
<input name="month" type="number">
<button type="submit">...</button>
Submits form when clicked!
Add a form
In index.html, add a form to submit new birthdays. The form should have the following traits:
Updating with db.execute
request.form.get("friend")
<input name="friend" type="text">
app.py
index.html
INSERT INTO table (column1, column2)
VALUES (value1, value2);
db = SQL("sqlite:///birthdays.db")
db.execute(...)
db.execute("SELECT * FROM birthdays WHERE month = ?", month)
db.execute("SELECT * FROM birthdays WHERE month = ? AND day = ?", month, day)
Update a database
In app.py, insert a new entry to the birthdays table of birthdays.db when the user submits data via POST:
Template Rendering
render_template("index.html",
message="Hello")
<p>The message is: {{ message }}</p>
app.py
index.html
The message is: Hello
render_template("index.html",
list=["Apple", "Banana"])
{% for item in list %}
<p>{{ item }}</p>
{% endfor %}
app.py
index.html
Apple
Banana
<p>Birthday month is {{ bday.month }}</p>
render_template("index.html",
bday={"month": "Feb", "day": 24})
app.py
index.html
Birthday month is Feb
{% ... %}
{{ ... }}
Jinja expressions (e.g., for)
Jinja variables (e.g., bday, message)
Render birthdays
In app.py and index.html, query for birthdays and display them in a table.
This is CS50 �Week 9