A browser interface for the pet database
Gregory S. DeLozier, PhD
From a working copy of
chapter-03-intro-to-web-apps/code:
http://127.0.0.1:5000/pets
The supplied pets.db holds the existing records.
Uniform Resource Locator (URL)
http://127.0.0.1:5000/pets
| Part | Meaning |
|---|---|
http |
Protocol scheme |
127.0.0.1 |
This computer’s loopback address |
5000 |
Port |
/pets |
Requested path |
GET /bye receives Bye!
@app.route("/hello/<name>", methods=["GET"])
def get_hello(name="world"):
return render_template("hello.html", name=name)/hello/Ada displays Hello, Ada! (from the
template)
cursor = connection.execute("select * from pet")
rows = cursor.fetchall()
return render_template("pets.html", pets=rows)(id, name, kind, age, food)
Each returned tuple becomes one displayed row.
{% for pet in pets %}
<tr>
{% for item in pet %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}{% ... %} controls the loop. {{ ... }}
inserts a value.
| Request | Function | Result |
|---|---|---|
GET /create |
get_create |
Blank form |
POST /create |
post_create |
Saved pet, then redirect |
Same path. Different methods and work.
<form action="/create" method="post">
<input name="name"/>
<input name="age"/>
<button type="submit">Create</button>
</form>data["age"] arrives as a string.
connection.execute(
"INSERT INTO pet(name, kind, age, food) "
"VALUES (?, ?, ?, ?)",
(data["name"], data["kind"],
data["age"], data["food"])
)
connection.commit()SQLite supplies the identifier.
GET /update/3
The loaded value becomes the form’s starting value.
GET /delete/3
connection.execute("DELETE FROM pet WHERE id = ?", (id,))
connection.commit()
return redirect(url_for("get_pets"))The refreshed list shows the remaining pets.
Request: Which path and method?
Route: Which values and database operation?
Response: A page, a redirect, or an error?
The database preserves state between requests.