25 Apr

Installing Django on Ubuntu, uWSGI, PostgreSQL, and Celery+Redis

1. Install Python3 (If not installed)
$ sudo apt-get update
$ sudo apt-get install python3 python3-dev
2. Install PostgreSQL
$ sudo apt-get update
$ sudo apt-get install postgresql postgresql-contrib libpq-dev

During the Postgres installation, an operating system user named postgres was created to correspond to the postgres PostgreSQL administrative user.
We need to change to this user to perform administrative tasks:

$ sudo su - postgres

Log into a Postgres session by typing:

$ psql

First, we will create a database for our Django project. Each project should have its own isolated database for security reasons.
We will call our database myproject in this guide, but it’s always better to select something more descriptive:

> CREATE DATABASE myproject;

Remember to end all commands at an SQL prompt with a semicolon.

Create a database user which we will use to connect to and interact with the database.

> CREATE USER myprojectuser WITH PASSWORD 'password';

Modify a few of the connection parameters for the user just created to speed up database operations.

We are setting the default encoding to UTF-8, and timezone to UTC which Django expects.
We are also setting the default transaction isolation scheme to “read committed”, which blocks reads from uncommitted transactions.

> ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
> ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
> ALTER ROLE myprojectuser SET timezone TO 'UTC';

Give our database user access rights to the database we created:

> GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

Exit the SQL prompt to get back to the postgres user’s shell session:

> \q

Exit out of the postgres user’s shell session to get back to your regular user’s shell session:

$ exit

Optionally Change the

$ sudo nano /etc/postgresql/X/main/pg_hba.conf
local all postgres peer

Should be:

local all postgres md5
  • If you can’t find this file, running ‘locate pg_hba.conf’ should show you where the file is.

After altering this file, restart PostgreSQL server.

$ sudo service postgresql restart.
3. Pull the project from Git store
$ cd ~
$ git clone https://gitlab.com/path/myproject.git
$ cd myproject/

Install Virtualenv

$ python3 -m venv venv
$ source venv/bin/activate
(venv) sudo -H pip3 install --upgrade pip
(venv) pip install -r requirements.txt
4. Configure the Django Database Settings

Now that we have a project, we need to configure it to use the database we created.

Install the psycopg2 package (if not in the requirement.txt) that will allow us to use the database we configured:

$ (venv) pip install psycopg2

Open the main Django project settings file located within the child project directory:

$ nano ~/myproject/myproject/settings.py
. . .

The simplest case: just add the domain name(s) and IP addresses of your Django server

ALLOWED_HOSTS = [ 'example.com', '']

To respond to ‘example.com’ and any subdomains, start the domain with a dot

ALLOWED_HOSTS = ['.example.com', '',]
ALLOWED_HOSTS = ['your_server_domain_or_IP', 'second_domain_or_IP', . . .]
. . .
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

Towards the bottom of the file, you will see a DATABASES section, change it to:

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

When you are finished, save and close the file.

5. Migrate the Database and Test your Project

Now that the Django settings are configured, we can migrate our data structures to our database and test out the server.

We can begin by creating and applying migrations to our database. Since we don’t have any actual data yet, this will simply set up the initial database structure:

$ cd ~/myproject
$ python manage.py makemigrations
$ python manage.py migrate

After creating the database structure, we can create an administrative account by typing:

$ python manage.py createsuperuser

Select a username, provide an email address, and password for the account.

Once you have an admin account set up, you can test that your database is performing correctly by starting up the Django development server:

$ python manage.py runserver

In your web browser, visit your server’s domain name or IP address followed by :8000 to reach default Django root page:

6. Install and Configure uWSGI
$ cd project/path
$ sudo pip3 install uwsgi
Test the uwsgi
$ uwsgi --http :8080 --home /home/myproject --chdir /home/myproject -w myproject.wsgi

Press CTRL+C to stop

Create uwsgi INI file

$ nano /etc/uwsgi/sites/myproject.ini
chdir = /home/myproject
home = /home/myproject/venv
module = myproject.wsgi:application
master = true
processes = 5

#socket = /run/uwsgi/myproject.sock
protocol = http # Must be set to use http socket with systemd
socket    = :8080
chmod-socket = 666
vacuum = true

die-on-term = true

To have uWSGI serve HTTP (instead of the binary uwsgi protocol) under Systemd socket activation, set protocol to http; for instance, in an INI, do this:

$ sudo nano /etc/systemd/system/uwsgi.service
Description=uWSGI Emperor
ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown www-data:www-data /run/uwsgi'
ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites


Make the file executable.

$ sudo chmod a+x /etc/systemd/system/uwsgi.service

Run the service

$ systemctl start uwsgi.service
$ systemctl status uwsgi.service
7. Install and Configure Nginx as a Reverse Proxy
$ sudo apt-get install nginx
$ sudo nano /etc/nginx/sites-available/myproject
server {
listen 80;
server_name myproject.com www.myproject.com;
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/myproject;

    location / {
        include         uwsgi_params;
        #uwsgi_pass      unix:/run/uwsgi/myproject.sock;
$ sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
$ sudo nginx -t
$ sudo service nginx restart
8. Troubleshoot

For NGINX errors

$ sudo tail -f /var/log/nginx/error.log

For others errors not in the standard log files

$ sudo tail -f /var/log/syslog
9. Using Celery and Redis for Background Task Processing

Step 1: Add celery.py

Inside the “myproject” directory, create a new file called celery.py:

$ nano ~/myproject/myproject/celery.py
from future import absolute_import
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
app = Celery('myproject')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings', namespace='CELERY')

def debug_task(self):
    print('Request: {0!r}'.format(self.request))

Step 3: Install Redis as a Celery “Broker”

$ sudo apt update
$ sudo apt install redis-server
$ sudo nano /etc/redis/redis.conf

The supervised directive is set to no by default. Since you are running Ubuntu, which uses the systemd init system, change this to systemd

$ sudo systemctl restart redis.service
$ sudo systemctl status redis
$ redis-cli> ping

Check the redis binding

$ sudo netstat -lnp | grep redis

Once Redis is up, add the following code to your settings.py file:

$ nano ~/myproject/myproject/settings.py

BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
'task1': {
'task': 'Joliba.tasks.task1',
'schedule': crontab(minute='*/10'),

Install the celery and redis package (if not in the requirement.txt)

(venv) $ pip install celery redis

Restart the uwsgi application

$ sudo systemctl restart uwsgi.service
10. Add SSL for the website using letsencrypt.

Adding SSL with Let’s Encrypt and NGINX

25 Feb

Migrating from Python 2.7 to Python 3.4

Last year, we made a decision to migrate to python 3.4 in 2016. This was not an easy decision as all our code base in developed using python 2.7 and it has served us very well.

Yesterday, We took the big step. This has already been delayed and was overdue.

First the Python 3.4 has to be installed, using the same process as in previous blog. However, replacing 2.7 with 3.4

the virtualenv has to be recreated for python 3.4.

pyvenv <virtual env>

thunder lock: disabled (you can enable it with --thunder-lock)
 uwsgi socket 0 bound to UNIX address xhod.sock fd 3
 Python version: 2.7.10 (default, Sep 21 2015, 12:21:01) [GCC 4.4.7 20120313 (Red Hat 4.4.7-16)]
 Set PythonHome to /home/uobis/webapps/xhod/venv
 ImportError: No module named site

I had to recompile uwsgi for python 3.4

/usr/local/bin/pip2.7 uninstall uWSGI

/usr/local/bin/pip3.4 install uWSGI

*** Starting uWSGI 2.0.12 (64bit) on [Thu Feb 25 22:31:10 2016] ***
compiled with version: 4.4.7 20120313 (Red Hat 4.4.7-16) on 25 February 2016 22:30:37
os: Linux-2.6.32-042stab108.8 #1 SMP Wed Jul 22 17:23:23 MSK 2015


02 Oct

Setting up Django on WebFaction’s Apache with mod_wsgi

If you want to run a Django application on WebFaction, you may simply use their automatic application creation scripts. Unfortunately, if you want to place your application in a Virtualenv, the automatic installer will not help you. I’m sure that WebFaction will eventually add an installer to set this up, but for now, you can use the following tutorial. In this text we set up a Django project in a Virtualenv running on WebFaction’s Apache with mod_wsgi.

Create a new application

Let’s begin by setting up a generic mod_wsgi application in your WebFaction control panel. Log into the control panel, choose the option to add a new application and specify the following settings:

  • Name: test_app
  • App category: mod_wsgi
  • App type : mod_wsgi 3.4 / Python 2.7

The new application will be created in your home directory (~) under: ~/webapps/test_app.

The directory will contain two subdirectories:

  • apache2 – contains the Apache configuration files (apache2/conf) and scripts which let you control the server (apache2/bin)
  • htdocs – contains default page files.

Configure a new website to hook up your application to a domain. Test the website by visiting it in your browser. You should be greeted by a message beginning with the following text:

Welcome to your mod_wsgi website! It uses: Python 2.7....

If you see the above, then the generic application is set up correctly and we can proceed to turn it into a Virtualenv Django application.

Remove htdocs

The htdocs directory will not be needed, so feel free to remove it.

$ cd ~/webapps/test_app
$ rm -r htdocs

Install Virtualenv

Check if Virtualenv is installed on your server:

$ virtualenv --version
-bash: virtualenv: command not found

If Virtualenv is installed, you will see a version number when running the above command. If it’s missing you’ll see a command not found error message instead.

Steps to install Vitrualenv on a WebFaction server are the following:

$ mkdir -p ~/lib/python2.7/
$ easy_install-2.7 pip
$ pip install virtualenv

If you get an permission denied error try this command to install virtualenv inside your user folder:

$  pip install --user virtualenv

Verify that installation was successful:

$ virtualenv --version

Create a virtual environment

Let’s proceed to turn our application directory into a virtual Python environment:

$ cd ~/webapps/test_app
$ virtualenv .

This adds the folders and scripts for a virtual environment inside of the directory which WebFaction created for our application.

You can now activate the created environment:

$ source bin/activate
(test_app) $

Install Django and other dependencies

Once the initial Virtualenv setup is complete, you can install Django inside it’s lib/python2.7/site-packages directory.

(test_app) $ pip install django

Verify that Django installed correctly:

(test_app) $ django-admin.py --version

Your project will probably depend on other packages. You can install those from a REQUIREMENTS.txt file, which you can generate on your development server with the pip freeze command.

(test_app) $ pip install -r REQUIREMENTS.txt

Start a Django project

Let’s create a new Django project inside the virtual environment:

(test_app) $ django-admin.py startproject test_django

Directory structure

At this stage you should have created a directory structure resembling


|-- apache2
|   |-- bin
|   |   |-- httpd
|   |   |-- httpd.worker
|   |   |-- restart             <== Scripts which start, stop and restart Apache
|   |   |-- start
|   |   `-- stop
|   |-- conf
|   |   |-- httpd.conf          <== Apache configuration file
|   |   `-- mime.types
|   |-- lib
|   |-- logs                    <== Apache error log is here
|   `-- modules
|-- bin                         <== Virtualenv scipts and binaries
|   |-- activate                <== Virtualenv activation script
|   |-- django-admin.py
|   |-- easy_install
|   |-- easy_install-2.7
|   |-- pip
|   |-- pip-2.7
|   |-- python -> python2.7
|   |-- python2 -> python2.7
|   `-- python2.7
|-- include
|-- lib
|   `-- python2.7
|       `-- site-packages       <== Virtualenv's Python packages directory
`-- test_django                 <== Your Django project directory
    |-- manage.py
    `-- test_django
        |-- __init__.py
        |-- settings.py
        |-- urls.py
        `-- wsgi.py             <== WSGI script file which Apache runs through mod_wsgi

Configure an Apache VirtualHost

We are now ready to configure Apache to serve our Django-powered webapp. In order to do this, we’ll need to modify the contents of the Apache configuration file located under apache2/conf/httpd.conf. Copy the original file to a backup for reference and make a note of the following values:

  • port number on which Apache listens to connections. This value is located in the line with the Listen directive of the original httpd.conf. In the example below we set this to 12345,
  • name of your application (test_app),
  • domain name which your website uses (example.com),
  • complete path to your application’s virtualenv and project directory: /home/my_username/webapps/test_app and /home/my_username/webapps/test_app/test_django,
  • complete path to your application’s WSGI script: /home/my_username/webapps/test_app/test_django/test_django/wsgi.py.

Use these values to customize the configuration template below and save it as your new httpd.conf:

1 import os
2 MEDIA_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../media/').replace('\\','/'))
3 STATIC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../static/').replace('\\','/'))

Save the configuration to ~/webapps/test_app/apache2/conf/httpd.conf and restart Apache.

$ ./apache2/bin/restart

Visit your website again and you should be presented with Django congratulating you for setting your server up correctly.

Serving static and media files

The recommended way to serve static and media files on WebFaction is to use Nginx directly.

1   ServerRoot "/home/my_username/webapps/test_app/apache2"
3   LoadModule dir_module        modules/mod_dir.so
4   LoadModule env_module        modules/mod_env.so
5   LoadModule log_config_module modules/mod_log_config.so
6   LoadModule mime_module       modules/mod_mime.so
7   LoadModule rewrite_module    modules/mod_rewrite.so
8   LoadModule setenvif_module   modules/mod_setenvif.so
9   LoadModule wsgi_module       modules/mod_wsgi.so
11  KeepAlive Off
12  Listen 12345
13  MaxSpareThreads 3
14  MinSpareThreads 1
15  ServerLimit 1
16  SetEnvIf X-Forwarded-SSL on HTTPS=1
17  ThreadsPerChild 5
19  WSGIRestrictEmbedded On
20  WSGILazyInitialization On
22  NameVirtualHost *
23  <VirtualHost *>
24      ServerName example.com
26      # Logging configuration
27      LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
28      CustomLog /home/my_username/logs/user/access_test_app.log combined
29      ErrorLog /home/my_username/logs/user/error_test_app.log
31      # Django WSGI settings
32      WSGIDaemonProcess test_app processes=5 python-path=/home/my_username/webapps/test_app/test_django:/home/my_username/webapps/test_app/lib/python2.7/site-packages:/home/my_username/webapps/test_app/lib/python2.7 threads=1
33      WSGIProcessGroup test_app
34      WSGIScriptAlias / /home/my_username/webapps/test_app/test_django/test_django/wsgi.py
35  </VirtualHost>

Let’s begin by creating the directories for static and media files.

$ cd ~/webapps/test_app
$ mkdir media static

In order to tell Django where the files should be stored, we should place the appropriate lines in the project’s settings.py file. I like to keep the location of media and static folders relative to the source code project, so I would set them in this way:

1   import os
2   MEDIA_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../media/').replace('\\','/'))
3   STATIC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '../../static/').replace('\\','/'))

Let’s collect the static files from all applications to the static directory:

$ cd ~/webapps/test_app
$ source bin/activate
(test_app) $ cd test_app
(test_app) $ python manage.py collecstatic

We can now serve our static files. In the WebFaction control panel, add two new applications named test_app_media and test_app_static. Both will be defined using these settings:

  • App category: Symbolic link
  • App type: Symbolic link to static-only app
  • Extra info: the path to the file folder, i.e. /home/my_username/webapps/test_app/media or /home/my_username/webapps/test_app/static

The final step is to add these Nginx-powered folders to our website definition. On the website settings screen for your domain, in the Contents section, choose to add an application. Choose the option to reuse an existing application and set the test_app_media to serve everything under http://example.com/media and test_app_static for http://example.com/static.


Contents section of website settings

Separating development and production settings

You will want to use slightly different settings for your development and production environments. In order to separate them you can create three separate settings files:

  • settings.py – global settings, which apply to both environments
  • settings_dev.py – your development environment specific settings
  • settings_prod.py – production environment specific settings

The settings_prod.py file should only contain the settings which are specific to this environment, but also import all the global settings. We can do this by importing global settings like this:

1   from .settings import *
3   # Define production-specific settings
4   DEBUG = False
8   # ... production server database settings ...
9   }

Django checks the environment variable named DJANGO_SETTINGS_MODULE to determine which settings file to use. If this environment variable is undefined, it will fall back to test_app.settings.

In order to use your new settings module in the shell, we can add a line to the end of the script which activates our virtual environment (bin/activate).

export DJANGO_SETTINGS_MODULE=test_app.settings_prod

Apache and mod_wsgi don’t know about our new settings yet. We can set the DJANGO_SETTINGS_MODULE dynamically inside the wsgi.py script. Create a wsgi_prod.py script which will contain the following:

1   import os
2   os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_app.settings_prod")
3   from django.core.wsgi import get_wsgi_application
4   application = get_wsgi_application()

Now instruct Apache to use this WSGI script by setting the WSGIScriptAlias directive line to:

1   WSGIScriptAlias / /home/my_username/webapps/test_app/test_django/test_django/wsgi_prod.py

Restart Apache and your application should run with production settings applied.

30 Nov

Deploying Flask on lighttpd

Deploying Flask seems a lonely taks, becuase of dearth of articles or blogs that explain in. This is even worse when deploying on a shared server.
Most people seems to treat a python deployment as a django deployment. Since, there are cheap and available Flask hsting site, i went with Django host, but confirmed that we can host any other framework.

The good thing is that, there too many similarities, and most packages are already installed on the host.

1. Open putty and log into the hosts server (s17.wservices.ch)
2. Check that the following following packages are installed

python and python-devel: the Python interpreter and its development package
lighttpd: The Lighty web server and its development package
install postgresql postgresql-contrib: The PostgreSQL database server and its development package
git: source code version control system (we will use it to download and update the application)
gcc: the C/C++ compiler (needed to compile Python extensions)
sudo: a tool that helps users run commands as other users.

If not, install them.

sudo apt-get python python-devel lighttpd httpd-devel mysql-server mysql-devel git gcc

3. Configure passwordless login (if needed)
4. Create a directory for the application, and install the application from BitBucket
mkdir app
cd app
git clone git://bitbucket.org/peppe/peppe-ng.git

5. Check User permissions
chmod -R 777 *

6. Setup the database
Go to https://panel.djangoeurope.com/databases/
Login with a username and password, and then create a database and dump the content of the dev db
pg_dump peppedb > ppdbdump.sql

Transfer the file to live host
sftp outfile.sql peppe@s17.wservices.ch

Load the Db on the live host
psql peppedb < ppdbdump.sql

7. Setup the webserver
Paste at the end of this file ~/lighttpd/lighttpd.conf

$HTTP[“host”] =~ “(^|.)peppe.com.ng$” {
fastcgi.server = (
“/flask.fcgi” => (
“main” => (
“socket” => env.HOME + “/mysite_project/mysite.sock”,
“check-local” => “disable”,
alias.url = (
“/media” => env.HOME + “/mysite_project/media”,

url.rewrite-once = (
“^(/media.*)$” => “$1”,
“^/favicon.ico$” => “/media/favicon.ico”,
“^(/.*)$” => “/flask.fcgi$1”,

Replace mydomain.com with the name of your domain. Be sure to escape all dots of your website’s name (put a backslash before it: .). Replace your_django_project/media with the path of you media directory (relative to your home directory). Replace mysite_project/mysite.sock with the path to your fastcgi socket file

Now you can launch your lighttpd:

~/init/lighttpd start

Whenever you make changes to the configuration, you can reload the configuration or restart lighttpd:

~/init/lighttpd reload

~/init/lighttpd restart

9. Configure the db and start
10. Install application updates

02 May

django and virtualenv on Aptana Studio

Create a folder for storing Virtualenv environments

C:Usersamachefe>mkdir env
C:Usersamachefe>cd env

Create a virtual environment VCMS by running the virtualenv command.
Windows PowerShell
Copyright (C) 2012 Microsoft Corporation. All rights reserved.
PS C:>
PS C:Usersamachefeenv>virtualenv vcms
New python executable in vcmsScriptspython.exe
Installing setuptools…………….done.
Installing pip……………….done.

In Microsoft Windows, before activating the virtual environment, ensure that the new environment is used by setting the Powershell execution policy
PS C:> Set-ExecutionPolicy RemoteSigned
PS C:> exit

Activate the virtualenv environment just created

PS C:Usersamachefeenv>vcmsScriptsactivate
(vcms) C:Usersamachefeenv>
(vcms) C:Usersamachefeenv>pip list

(vcms) C:Usersamachefeenv>pip show
ERROR: Please provide a package name or names.
(vcms) C:Usersamachefeenv>pip install django
Downloading/unpacking django
  Downloading Django-1.5.1.tar.gz (8.0MB): 8.0MB downloaded
   Running setup.py egg_info for package django

    warning: no previously-included files matching ‘__pycache__’ found under directory ‘*’
    warning: no previously-included files matching ‘*.py[co]’ found under directory ‘*’
Installing collected packages: django
  Running setup.py install for django

    warning: no previously-included files matching ‘__pycache__’ found under directory ‘*’
    warning: no previously-included files matching ‘*.py[co]’ found under directory ‘*’
Successfully installed django
Cleaning up…
Storing complete log in C:Usersamachefepippip.log

(vcms) C:Usersamachefeenv>

(vcms) C:Usersamachefeenv>pip list
Django (1.5.1)
(vcms) C:Usersamachefeenv>

Deactivate after installing

(vcms) C:Usersamachefeenv>deactivate

Setting up Aptana Studio

One of the best (and free) IDEs for is Aptana Studio. Aptana Studio is a complete environment that includes extensive capabilities to build Ruby and Rails, PHP, and Python applications, along with complete HTML, CSS and JavaScript editing. Aptana is based on Eclipse, and has one of the best python plugin, PyDev.
It has gives you two options for download. You can either install Aptana on top of your pre-existing Eclipse installation (Eclipse Plug-in Version), or install a standalone version of Eclipse with Aptana pre-configured. I prefer the stand alone version

To create a new Django project in Aptana, go to File->New -> Other. Select the PyDev folder, and finally, the PyDev Django Project option, and click next. Give the project a name.

Under the Interpreter, click to configure a new interpreter.

Hit New… Add Name for the interpreter, and specify a path to your newly made virtualenv. Click Ok

manually select the C:Python27Lib folder. Click OK

Click OK, to close the Python interpreter selector and return to the New Project box.

Select the Interpreter you just created in the last step, and Click Next. Complete the Requirement to create a project.
To test the project, Click the Aptana Studio RUN bottom

Aptana Studio Run button

Check if the project was successful from the browser

NB: You can also add a new Python Interpreter from Preferences > PyDev > Interpreter – Python settings.

10 Apr

Installing Django Framework using pip

The recommended way to install Django is with pip. pip is a tool for installing and managing Python packages.
Before installing Django, you need to install pip!

1. Install python
First things first – get Python! You can get the Python 2.7.3 (the current Python 2.x version as of this writing) 32-bit installer from http://python.org/download/.
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.
Type quit() to close the python interpreter
>>> quit()

NB: Before punning the command, remember to add the python on the windows environment PATH

2. Install Distribute. Distribute is a pre-requisite for pip
Download the distribute_setup.py file to you computer. Click on the file to install Distribute, or run from the command prompt.
C:>python distribute_setup.py
Extracting in c:usersamache~1appdatalocaltemptmpbjtb6b
Now working in c:usersamache~1appdatalocaltemptmpbjtb6bdistribute-0.6.36
Installing Distribute
Before install bootstrap.
Scanning installed packages
Setuptools installation detected at c:python27libsite-packages
Non-egg installation
Moving elements out of the way…
Already patched.
Installed c:python27libsite-packagesdistribute-0.6.36-py2.7.egg
Processing dependencies for distribute==0.6.36
Finished processing dependencies for distribute==0.6.36
After install bootstrap.
C:Python27Libsite-packagessetuptools-0.6c11-py2.7.egg-info already exists

3. Install pip
Now, Download the pip install script from GitHub.
Install by clicking the script or running from python command prompt

C:>python get-pip.py
Downloading/unpacking pip
  Downloading pip-1.3.1.tar.gz (247Kb): 247Kb downloaded
  Running setup.py egg_info for package pip

    warning: no files found matching ‘*.html’ under directory ‘docs’
    warning: no previously-included files matching ‘*.txt’ found under directory
    no previously-included directories found matching ‘docs_build_sources’
Installing collected packages: pip
  Running setup.py install for pip

    warning: no files found matching ‘*.html’ under directory ‘docs’
    warning: no previously-included files matching ‘*.txt’ found under directory
    no previously-included directories found matching ‘docs_build_sources’
    Installing pip-script.py script to C:Python27Scripts
    Installing pip.exe script to C:Python27Scripts
    Installing pip-2.7-script.py script to C:Python27Scripts
    Installing pip-2.7.exe script to C:Python27Scripts
Successfully installed pip
Cleaning up…

Test the installation

  pip <command> [options]

4. Install virtualenv (Not Compulsory, but very advised)
C:>pip install virtualenv
Install virtualenvwrapper  (for microsoft Windows)
C:>pip install virtualenvwrapper-win

And you are good to go!!

Thanks to tyler butler for his informative procedure