Notes

Developing Django in Production

May 15, 2020

Django is still my favorite web framework. While it comes with a neat system for rolling forward and back relational database schema migrations, you still have to populate your test and local databases with fixture data. Instead, you can use this script (configuration required) to connect your local django app to production to help test your code against production data:

#!/bin/bash

# Connect your local django app to a production database

set -ex

LOCAL_IP=127.0.0.1

# The local port that you want to use to forward to your production database
# This is set to the mysql default port, incremented by 1 so that it doesn't conflict with your local database
LOCAL_PORT=3307

# The remote host (or IP) that can access your production database
# This is probably where your app is hosted
REMOTE_HOST=example.com

# The ip that your production app uses to connect to your production database
REMOTE_IP=172.24.0.3

# The port that your production app uses to connect to your production database
REMOTE_PORT=3306

# Create an ssh tunnel from localhost to production
ssh -fNL $LOCAL_IP:$LOCAL_PORT:$REMOTE_IP:$REMOTE_PORT $REMOTE_HOST

# Reset everything when this script is killed
function cleanupSSH {
    pkill -f "$REMOTE_IP"
    rm .env
    ln -s .env.development .env
}
trap cleanupSSH EXIT

# Assuming you keep configs in .env, switch the symlink to a prodlocal config
# This is likely a mixture of development and production configs
rm .env
ln -s .env.prodlocal .env

# Start up django
./manage.py runserver