In order to also save the date when the poem was created, we can also create and save a date. Handling dates and times in software development is often a challenging task, given things like timezones, different formats for expressing date/time in different countries, etc, but there are libraries available in most programming languages that help with these things.
Python comes bundled with a number of libraries by default when you install it. These are referred to as the Python standard library. Other libraries need to be installed separately - you might remember that we installed a few of these, such as tweepy and peewee, during the install-fest portion before the Jumpstart program week.
The datetime library that we’ll use is part of the standard library. Let’s import it using the following in app.py.
import datetime
Then we can create a new datetime that contains the current date and time like this in app.py:
timestamp = datetime.datetime.now()
We can then add this to our Poem object in the “created_at” field so that this information is also stored in the database along with the poem text. The ORM will know how to map this to a format that SQLite will understand.
You can see the full code here:
# 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)
class Poem(Model):
body = CharField()
created_at = DateField()
class Meta:
database = db
if __name__ == '__main__':
app.run(debug=True)
Reload the page a number of times to create and save a bunch of new poems.
Let us know when you’ve created some new poems.
We’ve now added a complete new feature to save poems to the database, so now would normally be a good time to git add, commit, and push our changes. We’ll only do this once at the end of this section for this workshop.