Daniel Pullan

Trying is the first step towards failure.

Simpsons API

One of my most recents project was Simpsons API. It's a basic Flask application which I then put into a Docker Container.

The application itself

It's pretty simple, the core of the application is an array of quotes from The Simpsons.

quotes = ['I like my beer cold… my TV loud… and my homosexuals flaming.',
        'I am so smart. I am so smart. S-M-R-T, I mean S-M-A-R-T.', 
        'You’ll have to speak up. I’m wearing a towel.', 
        'Oh, look! Pantyhose. Practical and alluring']

This is then accessed by the secrets library and returned as a variable called data whilst our template is rendered.

@app.route('/')
def home():
    title = "Home"
    return render_template("index.html", data=secrets.choice(quotes), title=title)

Inside our template, we call our data with the open curly braces syntax.

<div class="row">
    <div class="col-12">

        <p>{{data}}</p>
    </div>
</div>

Which then gives us the final product, a randomly chosen quote from our array on a webpage.

You can also make a GET request to the $applicationURL/api (for example, curl app.3264.uk/api) thanks to these lines in our Flask application. This will also use the secrets library to randomly select a quote from our quotes array.

@app.route('/api')
def api(METHODS='get'):
    return secrets.choice(quotes)

Docker

This was my first time containeri[z/s]ing an application. The entire Dockerfile is just the below. I've commented to explain as best as I understand it

FROM python:latest # use the latest python docker image
WORKDIR /app # set your work directory within your container to be /app
RUN pip3 install flask # command to run when building the container. in this case, installing application dependancies
COPY . . # this one was weird, I'll explain below
CMD python3 flasky.py # command to run every time the container is run

Once I built the container a few times, destroyed it, made changes and built new containers, I quickly got comfortable with sending the resulting image to different servers and running them all over the shop.

COPY command

It's normal that a full-stop means "here". With the Dockerfile it means the same thing but in the COPY command, the first location is the host filesystem (the one building the container), the second location is the container filesystem. So whilst it reads like "copy from here to here", it's actually saying "copy from host filesystem to docker filesystem".

Final notes

Docker was fun to play with, I envision a lot more of it in the future. I'd like to look at Docker-compose and Kubernates as well. I had struggles with trying to protect my flask application with a letsencrypt certificate but apperantly you need to set up like a persistant docker file storage thing to keep the certificate in. I'll document that when I get round to it.