Now that we’ve done the initial setup to use our database and have a model, we can start saving the poems to the database.
# app.py
from flask import Flask, render_template, redirect, url_for, jsonify
import poembot
from peewee import *
app = Flask(__name__)
db = SqliteDatabase('poems.db')
@app.route('/')
def hello():
return "Hello world!"
@app.route('/poem')
def poem():
poem = poembot.generate_poem()
new_poem = Poem(body=poem)
new_poem.save()
return render_template('poem.html', poem=poem)
class Poem(Model):
body = CharField()
created_at = DateField()
class Meta:
database = db
if __name__ == '__main__':
app.run(debug=True)
To do this we create a new Poem (using the model we created) and pass the poem we generated in as the “body” of the Poem object. We store this new Poem object in the variable “new_poem”. We then call the .save() method on the new_poem variable to send it to the database.
Visit http://localhost:5000/poem to create a new poem, save it to the database, and display it in the browser. Reload the page a few times to create multiple new poems and save them to the database.
You can check that your poem was actually saved at the sqlite console. First open the sqlite console in a new terminal window:
sqlite3 poems.db
Then at the sqlite prompt query the database to get everything from the poem table:
sqlite> SELECT * FROM poem;
You should see your poem.
Let us know you’ve successfully queried your database and seen your poem.