-1

I am new to Python and Django. I am an IT professional that deploys software that monitors computers. The api outputs to JSON. I want to create a Django app that reads the api and outputs the data to an html page. Where do I get started? I think the idea is to write the JSON feed to a Django model. Any help/advice is greatly appreciated.

Here's a simple single file to extract the JSON data:

import urllib2
import json

def printResults(data):
    theJSON = json.loads(data)
    for i in theJSON[""]


def main():
    urlData = ""

    webUrl = urllib2.urlopen(urlData)
    if (webUrl.getcode() == 200):
        data = webUrl.read()
        printResults(data)
    else:
        print "Received error"

if __name__ == '__main__':
    main()
joshlsullivan
  • 1,375
  • 2
  • 14
  • 21
  • When you say _The api outputs to JSON_ it is like http://.../api/report and it returns a json? – Gocht Jul 07 '15 at 16:01
  • Check [django rest framework](http://www.django-rest-framework.org/) and also check [JsonResponse](https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects) and an [example](http://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python/24411716#24411716) – helado Jul 07 '15 at 16:03

1 Answers1

1

If you have an URL returning a json as response, you could try this:

import requests
import json

url = 'http://....'  # Your api url

response = requests.get(url)
json_response = response.json()

Now json_response is a list containing dicts. Let's suppose you have this structure:

[
  {
     'code': ABC,
     'avg': 14.5,
     'max': 30
  },
  {
     'code': XYZ,
     'avg': 11.6,
     'max': 21
  },
  ...
]

You can iterate over the list and take every dict into a model.

from yourmodels import CurrentModel

    ...
    for obj in json_response:
        cm = CurrentModel()
        cm.avg = obj['avg']
        cm.max = obj['max']
        cm.code = obj['code']
        cm.save()

Or you could use a bulk method, but keep in mind that bulk_create does not trigger save method.

Gocht
  • 9,924
  • 3
  • 42
  • 81