Bringing a Python Django app to Cloud Foundry in 2017

In this post I want to answer the question:
What do you have to do to run a Django web app on Cloud Foundry in 2017?

In the past, a few other people have described their approaches, but given that Cloud Foundry is continuously changing and improving, I thought it would be good to revisit the topic and learn about Python & Django support in 2017.

Python on Cloud Foundry

Cloud Foundry is a polyglot application deployment system. At Pivotal [disclosure: where I work, but not on the Cloud Foundry team], we put a lot of emphasis on how great a home Cloud Foundry is for Java Spring applications, and we’ve always been fond of Ruby on Rails.

That doesn’t mean other languages are hard to run on CF though. Following the example of Heroku, CF uses ‘buildpacks’ to provide official support for many languages, and community support for many more.

Python is an officially supported language for CF, and the official buildpack is maintained and updated by the buildpacks team. This gives me confidence that I can rely on the Python buildpack to have up-to-date interpreters and saves me the hassle of finding or creating a custom buildpack.

Pre-requisites

I’ve been going through the updated 2nd edition of the ‘Obey the Testing Goat book’ otherwise known as Test Driven Development With Python by Harry J.W. Percival.
Test Driven Development with Python

In the book you build up a Django application from scratch using a TDD approach. I’m going to deploy this ‘Superlists’ to-do list application on to Cloud Foundry.

If you want to follow along you should have completed all the exercises up to and including Chapter 10, which includes adding gunicorn to requirements.txt. You can take a look at my version of the app at this point.

If you want to skip ahead and see all the changes we’ll make to the app, have a look at this commit.

First we’ll start as always by checking that our functional tests run successfully on our local machine.

$ python manage.py test functional_tests

All green, so we’re good to go!

Getting ready for Cloud Foundry

We are going to push our application to Cloud Foundry which will create a domain name for us. Let’s use the STAGING_SERVER variable to test this. I am aiming for the domain ih-superlists.cfapps.io, yours will vary based on your Cloud Foundry provider.

$ STAGING_SERVER=ih-superlists.cfapps.io python manage.py test functional_tests

As expected the tests fail completely.

Let’s get started on deploying to Cloud Foundry. We need to provide a ‘manifest’ file which tells Cloud Foundry how to deploy our application.

manifest.yml

---
applications:
- name: ih-superlists
  memory: 512M
  instances: 1
  buildpack: python_buildpack
  command: gunicorn superlists.wsgi:application

Then you can try to deploy using $ cf push and look at the logs with $ cf logs ih-superlists.

If your CF setup is like mine you’ll see

... [APP/PROC/WEB/0] ERR   File "/home/vcap/app/lists/views.py", line 16
    [APP/PROC/WEB/0] ERR     return redirect(f'/lists/{list_.id}/')
    [APP/PROC/WEB/0] ERR                                         ^
    [APP/PROC/WEB/0] ERR SyntaxError: invalid syntax

Oops! We forgot that CF expects to run Python 2 applications by default (boo!). Let’s tell it our application doesn’t use legacy Python.

runtime.txt

python-3.6.2

And then $ cf push again.

We also need to add our domain to ALLOWED_HOSTS in our settings file.

superlists/settings.py

ALLOWED_HOSTS = ['ih-superlists.cfapps.io']

Now we can see our (non-CSS’d) site running at ih-superlists.cfapps.io! Let’s run our functional tests

$ STAGING_SERVER=ih-superlists.cfapps.io python manage.py test functional_tests

All three tests still fail!

Serving static files

One of the problems is that our static files are not being served properly. In our logs we can see the requests for our static files:

... [APP/PROC/WEB/0] ERR Not Found: /static/base.css
    [APP/PROC/WEB/0] ERR Not Found: /favicon.ico
    [APP/PROC/WEB/0] ERR Not Found: /static/bootstrap/css/bootstrap.min.css
    [APP/PROC/WEB/0] ERR Not Found: /static/base.css

The CF Python buildpack actually runs collectstatic as part of its process. Where are these files going? We can look inside the container by connecting with $ cf ssh ih-superlists.

The files are being collected during the staging process into /tmp/app/static, but this directory is not available in the eventual container that runs the application. Hence the lack of static files for our app!

Let’s collect our static files just before we start the gunicorn server instead.

manifest.yml

  command: python manage.py collectstatic --noinput && gunicorn superlists.wsgi:application

From the logs we can see that the static files are now in `/home/vcap/static’.

Side note: The VCAP acronym stands for VMware Cloud Application Platform, which was the original name of Cloud Foundry when it started at VMware.

We can run our functional tests again, or look at the live site and see that this hasn’t fixed our static files problem. We now have the static files, but they are not being served by gunicorn.

One way to fix this is to gather these files and serve them with another Cloud Foundry app which uses the static buildpack. We only expect a small amount of traffic for our application so in this case we can try to serve these files from the same server, using the Whitenoise Python library.

Add Whitenoise to your requirements.txt and then update the settings to include it in the Django middleware that is used.

$ pip install whitenoise
$ pip freeze | grep whitenoise >> requirements.txt

superlists/settings.py

MIDDLEWARE_CLASSES = [
  'django.middleware.security.SecurityMiddleware',
  'whitenoise.middleware.WhiteNoiseMiddleware',
  # ...
]

We can now see our site is served with CSS, but the functional tests still fail.

Adding a managed database

We can also see the problem in the logs.

... [APP/PROC/WEB/0] ERR django.db.utils.OperationalError: unable to open database file

Uh oh, we didn’t initialise our database. At this point we need to change from using the file based SQLite database which will be purged (along with all other files) each time we push the application. Let’s fix this by using data services provided with CF.

First let’s create a PostgreSQL database. Here I’m using the free tier provided by ElephantSQL on Pivotal Web Services.

$ cf marketplace
Getting services from marketplace in org ianhuston / space testing as XXX...
OK

service                       plans                                                                                description
...
elephantsql                   turtle, panda*, hippo*, elephant*                                                    PostgreSQL as a Service
...
* These service plans have an associated cost. Creating a service instance will incur this cost.

TIP:  Use 'cf marketplace -s SERVICE' to view descriptions of individual plans of a given service.

Let’s look at the ElephantSQL plans in depth:

$ cf marketplace -s elephantsql
Getting service plan information for service elephantsql as XXX...
OK

service plan   description                                            free or paid
turtle         4 concurrent connections, 20MB Storage                 free
panda          20 concurrent connections, 2GB Storage                 paid
hippo          300 concurrent connections, 100 GB Storage             paid
elephant       300 concurrent connections, 1000 GB Storage, 500Mbps   paid

Looks like the turtle plan will suit us. Let’s create a service on that plan.

$ cf create-service elephantsql turtle mydb

Next we attach this service to our app and restage as it suggests.

$ cf bind-service ih-superlists mydb
$ cf restage ih-superlists

We can now see our database connection variable in the environment of our app.

$ cf env ih-superlists
...
System-Provided:
{
 "VCAP_SERVICES": {
  "elephantsql": [
   {
    "credentials": {
     "max_conns": "5",
     "uri": SUPER_SECRET_URI
    },
    "label": "elephantsql",
    "name": "mydb",
    "plan": "turtle",
...

But how will our Django app know to use this database? We need to give these credentials to the application. One important thing to know is that the URI from the VCAP_SERVICES environmental variable will also be provided to our application in the DATABASE_URL variable. This is the same way Heroku apps receive database credentials and gives us the opportunity to use the small dj_database_url library from Kenneth Reitz.

Install the library using pip locally, add it to your requirements.txt and then let’s change our settings.

superlists/settings.py

import dj_database_url
...
#DATABASES = {
#    'default': {
#        'ENGINE': 'django.db.backends.sqlite3',
#        'NAME': os.path.join(BASE_DIR, '../database/db.sqlite3'),
#    }
#}

LOCAL_SQLITE='sqlite:///' + os.path.abspath(os.path.join(BASE_DIR, '../database/db.sqlite3'))
DATABASES = {}
DATABASES['default'] = dj_database_url.config(default=LOCAL_SQLITE)

The dj_database_url.config function automatically looks for the DATABASE environmental variable, and here we also give it a default to use when running locally. We should run our local tests again to check this still works.

Now we need to initialise our PostgreSQL database. We can do this using a once-off task with the relatively new cf task command. First push the application.

$ cf push ih-superlists

Then run the database initialisation as a task.

$ cf run-task ih-superlists "python manage.py migrate" --name migrate

You can check the status of a task by looking at $ cf tasks ih-superlists.

Once the migration task is finished, we can run our functional tests again.

$ STAGING_SERVER=ih-superlists.cfapps.io python manage.py test functional_tests

Success!

Let’s make one final change to turn off debug mode.

superlists/settings.py

DEBUG = False

Summary

Python & CF
We walked through a few steps there to get our Django app up and running on Cloud Foundry. Some of these are CF specific, and some are more about making our Django app more ‘cloud native’ in the spirit of the 12 factors. All the changes we made can be seen in this commit. You can also see all the code for the CF-enabled version of the Superlists app so far.

Let’s recap:

  1. Create a manifest.yml file with CF specific information.
  2. Create a runtime.txt file to specify Python version.
  3. Add your expected URL to ALLOWED_HOSTS
  4. Use Whitenoise to serve static files.
  5. Use a data service to create a database and connect it to Django.
  6. Initialise the database and run all migrations.
  7. Turn off debug mode.
  8. cf push your way to Django on CF!

Hopefully this is useful for you to get your Django app running on Cloud Foundry. Let me know in the comments if you have any other tips!

 

Python on Cloud Foundry

I’m very happy to be giving a talk at the latest PyData conference in New York this weekend.

This is a long post but I wanted a place to collect all the code I am showing in my talk and to provide a few more resources for those interested in trying out Python on Cloud Foundry further.

Resources Cloud Foundry

What is Cloud Foundry?

My talk is about how to use Python and the PyData stack on Cloud Foundry the open source cloud platform. Cloud Foundry started life at VMware and development transferred to Pivotal when it was formed. Cloud Foundry has grown much bigger since then with over 30 companies joining together to form the Cloud Foundry Foundation which will guide the development of the open source project.
Continue reading…

 

DataDive toolbelt

logo-datakindWhat tools do you need to bring to a DataDive? The next DataKind UK DataDive is taking place in two weeks time in London. I took part in one of the previous DataDives and I would highly recommend the experience for anyone with data science or analytical skills who wants to help charities use their data.

The DataDives take place over the course of a weekend and in that time you have to decide on a charity to work with, understand their data and goals, perform your analysis and present your results in a usable form. That’s a lot to get through in just over two days so it’s very important to be able to get up and running quickly with the analysis. I thought it might be useful to list the software and tools that I will be packing in my DataDive toolbelt this time around. Continue reading…

 

Pivotal Webinar, DS Amsterdam and PyData London

It looks like this is going to be a busy week. First up Noelle Sio, Alexander Kagoshima and I are presenting a webinar on Tuesday about our traffic analysis and prediction work. We talked about this topic at Strata Santa Clara but this webinar will take an extended look at the data, the challenges and the technology we used. You can sign up on the Pivotal website and the recording will be available afterwards.

Data Science AmsterdamOn Wednesday I am heading to Amsterdam to talk at the second Data Science Amsterdam meetup. The organisers of this meetup are branching out from their highly successful Data Science London event which regularly has hundreds of data scientists on the waiting list for each meeting. My talk on Wednesday will be about how to do massively parallel processing using familiar Python and R packages using the procedural languages PL/Python and PL/R.

On the subject of PL/Python, the video of my talk at PyData London is now available. Thankfully the video was edited to remove five minutes of me banging on the keyboard as my laptop crashed half way through my talk! In Amsterdam I will be talking about PL/R as well as PL/Python so hopefully this time the laptop holds up.

And finally, the PyData London conference was such a success that Ian Ozsvald and other organisers are starting a regular PyData meetup in London. We’re very excited at Pivotal to be hosting the first event in our London office on June 3rd. The meetup page is now up and places are filling up fast.

 

 
Bear