python3 urllib2,使用python3使用urllib或urllib2调用API+

博主在使用Python3尝试调用Azure Machine Learning API时遇到urllib问题,探讨了HTTPError的处理、urllib库的选择以及代码调试过程。寻求帮助解决语法错误和异常处理策略。
摘要由CSDN通过智能技术生成

尝试调用我的azuremlapi,但urllib有问题。我使用python3+,因此应该使用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。

问题似乎出在这条线上,所以我试着改变它:

^{pr2}$

有了这个:except urllib.request.HTTPError, error:

或者用这个:except urllib.HTTPError, error:

但没有效果

我得到的错误消息是:File "", line 37

except urllib2.HTTPError, error:

^

SyntaxError: invalid syntax

(第37行为上述“除外”)

我还试图完全删除第37行,但结果出现了以下错误:File "", line 43

print(json.loads(error.read()))

^

SyntaxError: unexpected EOF while parsing

意外的EOF通常是当我错过关闭一个(或一个{但我再次检查,并没有找到它。我希望有人能帮我找到问题所在。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值