S M Shamimul Hasan
S M Shamimul Hasan

Reputation: 6644

Python Data Uploading Error

By using python code, I am trying to read data from json files and uploading it through an API. However I am getting HTTP Error 5000. Following is my code:

    url = 'http://sipdev1.vbi.vt.edu:8080/EpiViewer/epiviewer/services/uploadGraphData'

    for i in json_file_name:
            json_data = open (i, 'r')
            lines=json_data.readlines()
            req = urllib2.Request(url)
            req.add_header('Content-Type','application/json')
            data = json.dumps(lines)
            response = urllib2.urlopen(req,data)

Here is the Error:

raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 500: Internal Server Error

Input file Example:

{
 "username": "xxxxx",
 "password": "yyyyy",
 "timeSeriesName": "Liberia_01-18-2015",
 "dataType": "Cases",
 "plotType": "Cumulative",
 "filename": "C_C.csv",
 "dateFormat": "MM-dd-yy",
 "forecastedOn": "01/18/2015",
 "visibility": "Public",
 "data": {
    "01-25-2015":"26 38 14",
    "02-01-2015":"22 33 11",
    "02-08-2015":"19 32 6",
    "02-15-2015":"17 32 2",
    "02-22-2015":"15 18 12",
    "03-01-2015":"14 26 2"
 }
}

I think code is not properly able to parse my input files. Do you have any idea about the solution?

Upvotes: 1

Views: 29

Answers (2)

John
John

Reputation: 2480

A 500 error indicates the server process crashed trying to parse your input. Your data either has extra keys, not enough keys or your data is formatted in a way not anticipated by the server.

Based on: lines=json_data.readlines() and data = json.dumps(lines)

It seems like you have not actually converted your data to a json object, and so cannot dump it from json either. Try replacing:

json_data = open (i, 'r')
lines=json_data.readlines()

with:

with open(i) as data_file: 
    json_data = json.load(data_file)

You should also use better names than i, and try/catch the errors associated with improperly formatted json files.

Also, you'll find the Requests library much easier to use for http APIs- see this:http://docs.python-requests.org/en/latest/

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121256

Your file is already encoded JSON. You do not need to encode it again. Send the file unchanged:

for name in json_file_name:
    with open(name) as json_data:
        data = json_data.read()
        req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
        response = urllib2.urlopen(req)

Upvotes: 1

Related Questions