Working with JSON and Django -
i new python , django. professional deploys software monitors computers. api outputs json. want create django app reads api , outputs data html page. started? think idea write json feed django model. help/advice appreciated.
here's simple single file extract json data:
import urllib2 import json def printresults(data): thejson = json.loads(data) 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()
if have url returning json response, try this:
import requests import json url = 'http://....' # api url response = requests.get(url) json_response = response.json()
now json_response
list
containing dicts
. let's suppose have structure:
[ { 'code': abc, 'avg': 14.5, 'max': 30 }, { 'code': xyz, 'avg': 11.6, 'max': 21 }, ... ]
you can iterate on list , take every dict model.
from yourmodels import currentmodel ... obj in json_response: cm = currentmodel() cm.avg = obj['avg'] cm.max = obj['max'] cm.code = obj['code'] cm.save()
or use bulk method, keep in mind bulk_create
not trigger save
method.
Comments
Post a Comment