Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making HTTP request with Django and deserializing output

So I'm almost totally new to web development as a whole, but have been thrown into a side project using Django to pull and parse data from a web service, and am struggling to understand exactly how things work, even while looking through the Django documentation.

In Django, I have everything set up and working at a basic level (using templates, a page is displayed saying "Hello World").

Now in order to pull the data from the webservice, I need to make a request to a URL of the following format:

http://wbsapi.withings.net/[service_name]?action=[action_name]&[parameters]

In the provided PHP example, they do this using cURL, and then json_decode.

What would I do to get similar functionality out of Django? Thanks in advance!

like image 388
elykl33t Avatar asked Jan 03 '13 16:01

elykl33t


1 Answers

You would use urllib2 and json standard modules (or, alternatively, the excellent library requests and json):

import urllib2
import json

url = 'http://wbsapi.withings.net/[service_name]?action=[action_name]&[parameters]'
serialized_data = urllib2.urlopen(url).read()

data = json.loads(serialized_data)

 

If you want it on a page, you want it in a view, which you will need to associate with an url.

Your urls.py will contain something like

from django.conf.urls import patterns, url, include

urlpatterns = patterns('',
    (r'^get_data/$', 'myapp.views.get_data'),
)

And your myapp/views.py will contain something like

from django.http import HttpResponse
import urllib2
import json

def get_data(request):
    url = 'http://wbsapi.withings.net/[service_name]?action=[action_name]&[parameters]'
    serialized_data = urllib2.urlopen(url).read()

    data = json.loads(serialized_data)

    html = "<html><body><pre>Data: %s.</pre></body></html>" % json.dumps(data, indent=2)

    return HttpResponse(html)

Of course, I don't know how you wanted your data to be displayed, so I just serialized it again :)

like image 110
Pavel Anossov Avatar answered Oct 16 '22 11:10

Pavel Anossov