Python Django Production Deploy with Apache

  1. Create github repo and clone locally
  2. Add .gitignore
  3. create virtualenv (mkvirtualenv envname)
  4. Set the correct virtualenv in PyCharm
  5. create database & users
  6. Update database settings (see below)
  7. First commit
  8. Add site and app
  9. Second commit

Some basic stuff

sudo su
apt-get install joe apache2 git python-setuptools python-dev python3 libapache2-mod-wsgi-py3

ssh-keygen -t rsa -C "email@domain.com"
# add the public key to your github account

Install Postgresql

apt-get install postgresql-server-dev-9.1
apt-get install postgresql postgresql-client
su - postgres
psql
CREATE USER flashcards WITH PASSWORD 'xxxx';
CREATE DATABASE flashcards;
GRANT ALL PRIVILEGES ON DATABASE flashcards to flashcards;
\list
\du
\q
cd /var/www/your_project
git clone git@github.com:wbrp/your_project.git

Install virtualenv

pip install virtualenvwrapper
source /usr/local/bin/virtualenvwrapper.sh
mkvirtualenv -p /usr/bin/python3.4 venv
workon venv
pip install -r requirements.txt

settings.py:

DATABASES = {
 'default': {
 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
 'NAME': 'mydb', # Or path to database file if using sqlite3.
 # The following settings are not used with sqlite3:
 'USER': 'myuser',
 'PASSWORD': 'password',
 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
 'PORT': '', # Set to empty string for default.
 }
 }

Add to site/wsgi.py

# Activate your virtual env
activate_env=os.path.expanduser("/opt/virtual_env/flashcards/bin/activate_this.py")
execfile(activate_env, dict(__file__=activate_env))

Make WSGI work

cat > /etc/apache2/conf.d/wsgipythonpath.conf
WSGIPythonPath /opt/virtual_env/flashcards/bin/python

a2enconf /etc/apache2/conf.d/wsgipythonpath.conf
service apache2 reload

Make cert

openssl genrsa -des3 -out server.key 2048
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Add new VirtualHost