Sunday, March 15, 2015

Django RESTful Example

The other topic covered in homework this week was setting up a RESTful service using Django. The example provided in the book is a Weather Station mock-up. I have implemented this example and made a few changes of my own to make it work. I did not use MySQL as the database back-end, which is not a hard requirement since Django's data representation libraries let you change the back-end without modifying the object structure. Code is here.

Setup Instructions

  1. Install Python 2.7 with Virtualenv extension
  2. 'virtualenv weatherstation' to create a new blank "weatherstation" Virtualenv container
  3. 'source weatherstation/bin/activate' to turn on Virtualenv container
  4. 'pip install -r requirements.txt' to install all the required packages for the Django setup
  5. 'python mange.py syncdb' to create a new database
  6. When prompted to add a new user, say 'yes' and use 'username' and 'password'

Running Instructions

  1. Activate the weatherstation Virtualenv container
  2. 'python manage.py runserver'
  3. Add at least one piece of data and browse to 'http://127.0.0.1:8000/home'

Adding Data

Modify the following line to as needed.

curl -i -H "Content-Type: application/json" -X POST -d '{"name":"TestCity", "timestamp": "123456", "temperature": "46", "lat": "30.123456", "lon": "76.123456"}' http://127.0.0.1:8000/station/ -u username:password

What's Happening Here?

The URI endpoint "/station" allows people with the correct permissions (username:password) to create new "Station" objects in Django using a POST request and a JSON object in the POST data. These objects contain a name along with some temperature and location information. When the /home URL is loaded, the "requests" Python library makes a GET request and displays the information from the last update using the "index.html" template. The values passed to the template from the view replace the {{ values }} of the same name.

No comments:

Post a Comment