ORM

While we used SQL to create our poem we thankfully will not need to use or know SQL to interact with our database. We’re going to use an Object Relational Mapper or ORM. An ORM makes it easy to query a database and retrieve data. The data is also returned in a way which makes it easy to work with in Python.

The ORM we’re going to use is named peewee.

We can include peewee in our application app.py by adding this line near the top:

from peewee import *

We also need to point the ORM to the database we created:

db = SqliteDatabase('poems.db')

There are lots of different ORMs to suit different tastes and some frameworks have a strong preference for using a specific ORM.

Here’s our full app.py code now with the lines we added highlighted:

# 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()
    return render_template('poem.html', poem=poem)

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