We can generate new poems and store them in our database, but we don’t have a way of seeing what poems are in our database through our application. Let’s create a new feature in our application that can show us.
For this we will need both a new route and a corresponding template to render the data.
Add a new route to your app.py application with this code:
@app.route('/poems')
def poems():
poems = Poem.select().order_by(Poem.id.desc())
return render_template('poems.html', poems=poems)
We’ve seen a lot of this before - we’re creating a new route at “/poems”, and we’re returning the poems within a template. The thing we haven’t seen before is the following line:
poems = Poem.select().order_by(Poem.id.desc())
We can use our model to make queries on the database. To do this, we call .select() on the model. We can also chain method calls to do additional things like order the list of what’s returned by certain criteria. When we store information in our database, an ID number is automatically assigned that begins at 1 and increments with each new record added. We’re asking it to sort by this ID number in descending order, so that new records will appear at the beginning of the list.
Here’s what our full application code looks like now:
# app.py
from flask import Flask, render_template, redirect, url_for, jsonify
import poembot
from peewee import *
import datetime
app = Flask(__name__)
db = SqliteDatabase('poems.db')
@app.route('/')
def hello():
return "Hello world!"
@app.route('/poem')
def poem():
poem = poembot.generate_poem()
timestamp = datetime.datetime.now()
new_poem = Poem(body=poem, created_at=timestamp)
new_poem.save()
return render_template('poem.html', poem=poem)
@app.route('/poems')
def poems():
poems = Poem.select().order_by(Poem.id.desc())
return render_template('poems.html', poems=poems)
class Poem(Model):
body = CharField()
created_at = DateField()
class Meta:
database = db
if __name__ == '__main__':
app.run(debug=True)
So we expect with this route that we’ll be able to see the list of poems at /poems.
Try it: http://localhost:5000/poems
You get an error. What went wrong? Type into chat or unmute with what you think you need to do to resolve this issue.