Monday, December 22, 2014

Install django in virtual environment


# Pre req:

I am using ubuntu 10.10 for this tutorial. Setup environment for python

# Install Django:
   Run below commands to setup django and create my first app

  pip install django

# Create test project 

  django-admin.py startproject testsite

It will create the testsite as project. Each project consist of many sub projects call apps. Lets create a app and call it soapapp, Which will take input soap requests. and will response json. I will write a blog on it latter on.

python manage.py startapp soapapp

Use terminal and write these command
>> ls
  
you will see component if django app like views, models, tests with (py) extensions, ofcourse it is python project

Views.py

So in views. py we will create a view. A simple code that will response ok is attached

import json
from django.http import HttpResponse

def hello(request):
    response_data = {}
    response_data['result'] = '200'
    response_data['message'] = 'ok'
    return HttpResponse(json.dumps(response_data), content_type="application/json")
URLs.py

Lets create urls class, where we will register url for above create view.

from django.conf.urls import patterns, url
from views import *

urlpatterns = patterns('soapapp.views',
   url(r'^hello$', 'hello', name='hello'),
)

Register this url file in main app urls.py
 
so from command line open

/venv_hello/testsite/testsite$ sudo gedit urls.py &
And append this line in url

url(r'^soap/', include('soapapp.urls')),

Run app:

To run this app open email folder, root of the app, as we have testsite. There type command
sudo python manage.py runserver
you can see reponse http://127.0.0.1:8000/soap/hello



You can download sample project from this link.

References 

# http://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python