List Route

We can generate new talks and store them in our database, but we don’t have a way of seeing what talks 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('/talks')
def talks():
    all_talks = Talk.select().order_by(Talk.id.desc())

    return render_template('talks.html', talks=all_talks)

We’ve seen a lot of this before - we’re creating a new route at “/talks”, and we’re returning the talks within a template. The thing we haven’t seen before is the following line:

all_talks = Talk.select().order_by(Talk.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 other 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. We store the list of results returned from the database in a variable called “all_talks”.

Here’s what our full application code looks like now:

# app.py

from flask import Flask, render_template, redirect, url_for, jsonify, request
from talk_mashup_bot import talk_mashup_bot
from peewee import *
import datetime

app = Flask(__name__)
db = SqliteDatabase('talks.db')

@app.route('/')
def hello():
    return "Hello world!"

@app.route('/talk/new')
def new_talk():
    title = talk_mashup_bot.generateTitle()
    return render_template('new_talk.html', title=title)

@app.route('/talk', methods=['POST', 'GET'])
def talk():
    if request.method == 'GET':
        return redirect(url_for('new_talk'))

    talk_title = request.form['form-title']
    talk_description = request.form['form-description']
    talk_timestamp = datetime.datetime.now()

    new_talk = Talk(title=talk_title, description=talk_description, created_at=talk_timestamp)
    new_talk.save()

    return render_template('talk.html', title=talk_title, description=talk_description, timestamp=talk_timestamp)

@app.route('/talks')
def talks():
    all_talks = Talk.select().order_by(Talk.id.desc())

    return render_template('talks.html', talks=all_talks)


class Talk(Model):
    title = CharField()
    description = CharField()
    created_at = DateField()

    class Meta:
        database = db

if __name__ == '__main__':
    app.run(debug=True)

Trying It

So we expect with this route that we’ll be able to see the list of talks at /talks.

Try it: http://localhost:5000/talks