3

Trying to call my Azure ML api, but I have problem with urllib. I use Python 3+ and should therefore use urllib instead of urllib2, but I am confused about what happens in urllib and why I get the error message I get.

Full script:

import urllib2
# If you are using Python 3+, import urllib instead of urllib2

import json 


data =  {

    "Inputs": {

            "input1":
            {
                "ColumnNames": ["x", "x", "x"],
                "Values": [ ["x", "x", "x"]
            },        },
        "GlobalParameters": {
}
}

body = str.encode(json.dumps(data))

url = 'https://ussouthcentral.services.azureml.net/workspaces/xxxxxxxxxxxxxxxxxxx/services/xxxxxxxxxxxxxxxxxxxxx/execute?api-version=2.0&details=true'
api_key = 'xxxxxx'
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}

req = urllib.request.Request(url, body, headers) 

try:
    response = urllib.request.urlopen(req)


    result = response.read()
    print(result) 
except urllib2.HTTPError, error:
    print("The request failed with status code: " + str(error.code))
    print(error.info())
    print(json.loads(error.read()))   

In the documentation for the API it says I should use urllib.request. The problem seems to be this line, so I tried changing it:

except urllib2.HTTPError, error:  

With this:

except urllib.request.HTTPError, error:

Or with this:

except urllib.HTTPError, error:  

But to no effect

The error message I get is:

  File "<ipython-input-14-d5d541c5f201>", line 37
    except urllib2.HTTPError, error:
                            ^
SyntaxError: invalid syntax

(line 37 is the "except" described above)

I also tried to delete row 37 entirely but it resulted in this error:

  File "<ipython-input-15-6910885cb679>", line 43
    print(json.loads(error.read()))
                                   ^
SyntaxError: unexpected EOF while parsing

Unexpected EOF is usually when I missed to close an ( or an { but I double checked and cant find it. I hope someone will be able to help me find the issue.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Please, don't use an unbound `str` method unless that's the only way to apply the method. Also, name your codec explicitly, don't rely on a default. Just use `body = json.dumps(data)).encode('utf8')` here. – Martijn Pieters Nov 26 '18 at 15:25

1 Answers1

2

The error message is pretty clear: there is a syntax error (so this issue is not related to urllib at all). Change the conflicting line by this other one and it should work:

...    
except urllib2.HTTPError as error:
    # your error handling routine

Also, take a look to the Python docs regarding how to handle exceptions https://docs.python.org/2/tutorial/errors.html#handling-exceptions

Cartucho
  • 3,257
  • 2
  • 30
  • 55