FlowFX

Continuous deployment of a Django app from Travis CI to PythonAnywhere

This post describes the configuration of a continuous deployment pipeline that deploys a Django project from GitHub via Travis CI to PythonAnywhere.

All code samples come from a pet project of mine: Unkenmathe (GitHub repository).

Please note that this is no introduction to Travis CI, PythonAnywhere nor Git.

Here are the steps that I take.

1. Deploy Django project

PythonAnywhere's guide for Deploying an existing Django project on PythonAnywhere explains everything to manually set up the web app.

For reference, the Unkenmathe code is checked out to

/var/www/sites/unkenmathe.de

and the virtual environment lives at

~/.virtualenvs/unkenmathe.de/

2. Prepare Git push deployment

PythonAnywhere has a comprehensive guide to set up Git push deployments.

My bare repository is located at

~/bare-repos/unkenmathe.git

The post-receive hook looks like this:

# ~/bare-repos/unkenmathe.git/hooks/post-receive
#!/bin/bash

BASE_DIR=/var/www/sites/unkenmathe.de
PYTHON=$HOME/.virtualenvs/unkenmathe.de/bin/python
PIP=$HOME/.virtualenvs/unkenmathe.de/bin/pip
MANAGE=$BASE_DIR/manage.py

echo "=== configure Django ==="
export DJANGO_SETTINGS_MODULE=config.settings.production

echo "=== create base directory ==="
mkdir -p $BASE_DIR

echo "=== checkout new code ==="
GIT_WORK_TREE=$BASE_DIR git checkout -f

echo "=== install dependencies in virtual environment ==="
$PIP install -q -r $BASE_DIR/requirements/production.txt

echo "=== collect static files ==="
$PYTHON $MANAGE collectstatic --no-input

echo "=== update database ==="
$PYTHON $MANAGE migrate --no-input

3. Custom deployment with Travis CI

I set up the repository in Travis CI for automatic builds on pull requests and branch pushes. In order to deploy to PythonAnywhere, I use Travis's Custom deployment.

All Travis related files live in the .travis subdirectory of the Django project. This is of course completely arbitrary.

~ $ cd ~/code/unkenmathe/
unkenmathe $ mkdir .travis
unkenmathe $ cd .travis

Create SSH keys

git push uses SSH, so I need a pair of SSH keys.

.travis $ ssh-keygen -t rsa -b 4096 -C 'hallo@example.com' -f deploy_key

Copy the public key to the PythonAnywhere account (see PythonAnywhere: SSH access).

.travis $ ssh-copy-id -i deploy_key flowfx@ssh.pythonanywhere.com

Encrypt SSH key and add it to the repository

Travis offers a tool to encrypt files that allows to add the SSH private key to the Git repository. See Encrypting files for a complete how-to.

First, I encrypt the deploy key,

.travis $ travis login
.travis $ travis encrypt-file deploy_key --add

then add it to the Git repository.

.travis $ git add deploy_key.enc

Last, I make sure the decrypted key is never pushed to the public GitHub repository:

unkenmathe $ echo 'deploy_key' >> .gitignore

Configure Travis CI

A simplified .travis.yml configuration file (here the one used for Unkenmathe) looks like this. The before_install part is added automatically by the travis encrypt-file deploy_key --add command. The ssh_known_hosts line is also required for push deployment with Git/SSH.

Hopefully, the rest is documented sufficiently by the comments.

# .travis.yml
language: python
cache: pip
python:
- 3.6
addons:
  # add PythonAnywhere server to known hosts
  ssh_known_hosts: ssh.pythonanywhere.com
before_install:
  # decrypt ssh private key
  - openssl aes-256-cbc -K $encrypted_xxxxxxxxxxxx_key -iv $encrypted_xxxxxxxxxxxx_iv -in .travis/deploy_key.enc -out deploy_key -d
install: pip install -r requirements/testing.txt
script:
  # run test suite
  - pytest --cov
after_success:
  # start ssh agent and add private key
  - eval "$(ssh-agent -s)"
  - chmod 600 deploy_key
  - ssh-add deploy_key
  # configure remote repository
  - git remote add pythonanywhere flowfx@ssh.pythonanywhere.com:/home/flowfx/bare-repos/unkenmathe.git
  # push master branch to production 
  - git push -f pythonanywhere master
  # reload PythonAnywhere web app via the API
  - python .travis/reload-webapp.py
after_deploy:
  # update coveralls.io
  - coveralls
notifications:
  # spare me from email notifications
  email: false

Reload web app

The after_success step includes a call to .travis/reload-webapp.py, which is a Python script that reloads the web app via the PythonAnywhere API. This is more or less copied directly from the documentation.

# .travis/reload-webapp.py
"""Script to reload the web app via the PythonAnywhere API.

"""
import os
import requests

my_domain = os.environ['PYTHONANYWHERE_DOMAIN']
username = os.environ['PYTHONANYWHERE_USERNAME']
token = os.environ['PYTHONANYWHERE_API_TOKEN']

response = requests.post(
    'https://www.pythonanywhere.com/api/v0/user/{username}/webapps/{domain}/reload/'.format(
        username=username, domain=my_domain
    ),
    headers={'Authorization': 'Token {token}'.format(token=token)}
)
if response.status_code == 200:
    print('All OK')
else:
    print('Got unexpected status code {}: {!r}'.format(response.status_code, response.content))

Set environment variables

To make all this actually work, you need to set some environment variables in the Travis project settings. Namely PYTHONANYWHERE_DOMAIN, PYTHONANYWHERE_USERNAME and PYTHONANYWHERE_API_TOKEN.

Also, don't forget to set DJANGO_SECRET_KEY!

Summary

These are the resources you need:

PythonAnywhere

Travis CI

Future

I need to look into Travis's Script deployment which looks like a much cleaner way to run the deployment commands.

Comment!

If you find the one error that I missed, please tell me about it!

Updates

Use Django in-memory file storage with pytest

In my current project, I create PDF files from Jinja2/LaTeX templates. In each test run, several PDFs are created and saved to disk. How do you test this without filling up the hard drive?

I use an in-memory data storage. For Django there is a package that makes it really easy: dj-inmemorystorage.

A non-persistent in-memory data storage backend for Django.

Using pytest fixtures:

# tests/conftest.py
import pytest
import inmemorystorage

from django.conf import settings

@pytest.fixture
def in_memory():
    settings.DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'

That's it. When using this in_memory fixture in a test function, the files will never be written on disk.

Update 5/9/2017

It's actually much easier than this. I now configure the in-memory file storage directly in the Django configuration file that pytest uses.

# config/settings/testing.py
"""Django configuration for testing and CI environments."""
from .common import *

# Use in-memory file storage
DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'

Neue Podcastfolgen Juli 2017

Nach langen Monaten habe ich diese Woche gleich zwei neue Podcastepisoden veröffentlicht.

Mexiko

Schon im Januar hatte ich die zweite Folge von Tacos und Limetten aufgenommen. Es wurden zweieinhalb spannende Stunden über die Geschichte und Gesellschaft Mexikos. Außerdem gibt's Reisetipps!

C3S

Und auch der C3S-Podcast ist wieder am Start. In der neuen Episode berichtet mir m.eik von der letzten Generalversammlung und den Wirren der deutschen Gesetzgebung in Sachen Verwertungsgesellschaften.

Reggae Freiburg

Reggae Freiburg hat ein neues Zuhause und läuft endlich unter der würdigen Domain

[**www.reggae-freiburg.de**](http://www.reggae-freiburg.de/)

Checkt das!

Install an extra LaTeX font package on PythonAnywhere

This week I installed a LaTeX font package in my PythonAnywhere account. The TL;DR: just install it manually.


I've been using LaTeX on and off for more than 10 years now. But I never dove into the depths of the system, typesetting mathematical expressions was fun enough for me.

So I rely on Google a good bit. But that's fine, as there are always new things to discover. Plus: the PythonAnywere support is superb! I had a very helpful email exchange with Giles. Thanks!

Using the TeXLive distribution on my Mac, and on the Ubuntu server that runs PythonAnywhere, the way to install packages nowadays is to use the tlmgr command, which I can only assume to be an abbreviation for TeX Live manager.

$ tlmgr install roboto

Well, that didn't work, because I am not root nor sudo. Turns out, there is a tlmgr User Mode which, after initializing a local user tree

$ tlmgr init-usertree

allows me to install additional LaTeX packages into my home directory under ~/texmf. So:

$ tlmgr --usermode install roboto

should have done it. Unfortunately I got the following error message.

$ tlmgr --usermode install roboto
/usr/bin/tlmgr: could not find a usable xzdec.
/usr/bin/tlmgr: Please install xzdec and try again.

Thanks to Giles, it was easy to install the missing xz package.

$ wget https://tukaani.org/xz/xz-5.2.3.tar.gz
$ tar xf xz-5.2.3.tar.gz 
$ cd xz-5.2.3/
$ ./configure --prefix=$HOME/.local
$ make
$ make install

That actually worked. But then tlmgr spit out this:

Unknown directive ...containerchecksum
06c8c1fff8b025f6f55f8629af6e41a6dd695e13bbdfe8b78b678e9cb0cfa509826355f4ece20d8a99b49bcee3c5931b8d766f0fc3dae0d6a645303d487600b0..., please fix it! at /usr/share/texlive/tlpkg/TeXLive/TLPOBJ.pm line 210, <$retfh> line 5761.

This is a clear case for Google, and Google didn't disappoint. The installed version of Tex Live is from 2013 and doesn't work with the current package repositories.

$ tlmgr --version
(running on Debian, switching to user mode!)
tlmgr revision 32912 (2014-02-08 00:49:53 +0100)
tlmgr using installation: /usr/share/texlive
TeX Live (http://tug.org/texlive) version 2013

After setting the repository to an old archived one,

$ tlmgr option repository ftp://tug.org/historic/systems/texlive/2013/tlnet-final

the TeX Live installation was happy.

But, it turns out, the 2013 repository doesn't even include the roboto font package. So…

TL;DR

… in the end, I installed the font by hand, following the instructions here: http://www.ctan.org/tex-archive/fonts/roboto/.

$ wget http://mirror.ctan.org/install/fonts/roboto.tds.zip
$ cd ~/texmf
$ unzip ~/roboto.tds.zip
$ texhash
$ updmap --enable Map=roboto.map

And now I have the roboto font available for pdflatex on PythonAnywhere!