Skip to main content

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.

  1. Install pip, the tool for installing & managing Python packages
    sudo apt-get install python-pip
  2. Install virtualenv and virtualenvwrapper.
    sudo pip install virtualenv
    sudo pip install virtualenvwrapper
  3. Create the virtual environment, in this case myenv
    virtualenv myenv
  4. 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:
  5. 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.
  6. 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.
    sudo apt-get install python-dev libmysqlclient-dev
    sudo apt-get build-dep python-mysqldb
    sudo pip install pip --upgrade
    pip install MySQL-python
    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
  7. Verify that MySQLdb is indeed installed correctly and accessible from Python by launching Python interpreter and importing it. You should see something like:
    Python 2.7.3 (default, Sep 26 2013, 20:08:41)
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import MySQLdb
    Note how importing the moduld does not result in errors indicating that the installation was successful.