Save

Now that we’ve done the initial setup to use our database and have a model, we can start saving the talks to the database.

# app.py

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

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']

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

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

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

    class Meta:
        database = db

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

To do this we create a new Talk (using the model we created) and pass the title we pulled from the HTML form the “title” of the Talk object, and the description that we also pulled as the “description” of the Talk object. We store this new Talk object in the variable “new_talk”. We then call the .save() method on the new_talk variable to send it to the database.

Visit http://localhost:5000/talk/new to create a new talk, save it to the database, and display it in the browser. Submit the form a few times to create multiple new talks and save them to the database.

You can check that your talk was actually saved at the sqlite console. First open the sqlite console in a new terminal window:

sqlite3 talks.db

Then at the sqlite prompt query the database to get everything from the talk table:

sqlite> SELECT * FROM talk;

You should see your talk.