Refactoring

Now we want to use the code we created in the twitter poembot workshop to create a poem in our web application. We could just paste that code into our /poem route function. The problem with that is that our app.py file begin to get long…

So we edit a file named poembot.py to look like the following:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# tweets one variant of This Is Just To Say by William Carlos Williams
# original: https://poets.org/poem/just-say

import requests
from random import randint
#from credentials import *
import tweepy
#auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
#auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
#api = tweepy.API(auth)

def generate_poem():
    # gather some corpora from GitHub using requests; these are in JSON format
    fruit_response = requests.get('https://raw.githubusercontent.com/dariusk/corpora/master/data/foods/fruits.json')
    adjectives_response = requests.get('https://raw.githubusercontent.com/dariusk/corpora/master/data/words/adjs.json')
    colors_response = requests.get('https://raw.githubusercontent.com/dariusk/corpora/master/data/colors/crayola.json')

    # Extract a Python-readable list from each response
    fruits = fruit_response.json()['fruits']
    adjectives = adjectives_response.json()['adjs']
    colors = colors_response.json()['colors']

    # Pick random numbers
    fruit_num = randint(0, len(fruits)-1)
    adjectives_num = randint(0, len(adjectives)-1)
    color_num = randint(0, len(colors)-1)

    # Choose random items from each list using random numbers
    fruit_chosen = fruits[fruit_num].lower()
    color_chosen = colors[color_num]['color'].lower()
    adjective_chosen = adjectives[adjectives_num].lower()

    # Fill in the blanks of the poem with the randomly chosen items
    # \n means line break
    # \ at end of line just splits the line in the code, so that the code can be read more easily

    poem = 'This is just to say\n\n\
    I have eaten\n\
    the {0}s \n\
    that were in\n\
    the icebox \n\n\
    and which\n\
    you were probably\n\
    saving\n\
    for breakfast\n\n\
    Forgive me\n\
    they were delicious\n\
    so {1} \n\
    and so {2}' \
       .format(fruit_chosen, color_chosen, adjective_chosen)

    #api.update_status(status=poem)
    return poem

## SAMPLE OUTPUT

## I have eaten
## the kumquats
## that were in
## the icebox
##
## and which
## you were probably
## saving
## for breakfast
##
## Forgive me
## they were delicious
## so unmellow yellow
## and so waterproof

Note that for sake of the workshop to this point we’ve commented out the sections where we actually send the poem to Twitter.

To create a new file in VSCode:

  1. from the menu File > New File > Text Editor.
  2. Copy the code from above and paste it into VSCode.
  3. File > Save. Name the file poembot.py

What’s Here?

The lines to really look closely at are:

def generate_poem():

The above defines a function which allows the code within to be reused.

And instead of updating the status via the Twitter API we’re going to use our function to return the text of the poem like this:

return poem

You should now have two files in a single directory:

  • app.py - your Flask application
  • poembot.py - a module which provides a function for generating a new poem

Trying It

One nice thing about a module like this is that you can now use it in more than one place without duplicating code.

Now type import poembot

We can now use our module to create a poem: poembot.generate_poem()

  1. View > Terminal
  2. One the right side of your VSCode terminal click the + sign to open a new terminal.
  3. In the terminal type python and hit enter. You’ll enter an interactive session in python.
  4. In the terminal type import poembot and hit enter.
  5. In the terminal type poembot.generate_poem()

You should see that a poem was generated.