Search This Blog

Setting up Ubuntu for Python Development

This is more for my own reference as I often forget the various steps that I followed to get an environment set up. This post lists the steps that I followed to setup an Ubuntu Server for Python/Django/MySQL environment. The steps are drawn from various resources on the web -- official documentation from Ubuntu, some blog posts and a few pointers on stackexchange/stackoverflow. All credits due to all the kind souls who shared knowledge.

The environment that I want is Ubuntu Server, Python, Django with MySQL support. MySQL support is through MySQLdb.

These are the steps I followed on Ubuntu Server 12.04 LTS with MySQL. All commands are run from the home folder unless otherwise specified.

Install pip, the tool for installing & managing Python packages

sudo apt-get install python-pip

Install virtualenv and virtualenvwrapper.

sudo pip install virtualenv
sudo pip install virtualenvwrapper

Create the virtual environment, in this case myenv

virtualenv myenv

Activate the newly created virtual environment, so that Django and other dependent components will be installed to this virtual environment and not to the system-wide python folders.

source myenv/bin/activate

This should cause the shell prompt to be prefixed with (myenv) as in:

(myenv)hari@devmachine:~$

Install Django in the newly created virtual environment

pip install django

Note that we don't prefix the command with sudo here as Django is being installed to the virtual environment in our home folder.

Now we need to install the MySQL ORM module for Python so that we can access MySQL DB from inside Django. Unfortunately, Django does not come pre-built with this module. Neither does the standard Python 2.7, that is installed with Ubuntu installation.

MySQL interface from Python is through MySQLdb and this package is provided in source form. So when you install it, the installation attempts to compile the source files. These sources include a C file which links to the MySQL client libraries. This is why you have to install the libmysqlclient-dev package in the beginning followed by the build-dep python-mysqldb which installs gcc (if it's not already installed). Finally, we make sure pip is of the latest version before instructing it to install MySQL-python

Verify that MySQLdb is indeed installed correctly and accessible from Python by launching Python interpreter and importing it. You should see something like: