使用Python 3+用urllib或urllib2调用API

时间:2018-11-26 13:41:56

标签: python urllib

尝试调用我的Azure ML API,但是urllib出现问题。我使用的是Python 3+,因此应该使用urllib而不是urllib2,但是我对urllib中发生的事情以及为什么收到错误消息感到困惑。

完整脚本:

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()))   

在API文档中,我说我应该使用urllib.request。 问题似乎是这条线,所以我尝试更改它:

except urllib2.HTTPError, error:  

与此:

except urllib.request.HTTPError, error:

或与此:

except urllib.HTTPError, error:  

但没有效果

我收到的错误消息是:

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

(第37行是上述的“除外”)

我也尝试完全删除第37行,但导致此错误:

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

意外的EOF通常是我错过关闭(或{但我仔细检查并找不到它的时候。我希望有人能够帮助我找到问题。

1 个答案:

答案 0 :(得分:2)

错误消息非常清楚:存在一个语法错误(因此,此问题与urllib根本无关)。通过另一条更改冲突线,它应该可以工作:

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

还请查看有关如何处理异常https://docs.python.org/2/tutorial/errors.html#handling-exceptions

的Python文档
相关问题