urllib2不会将http NO_CONTENT(204)作为成功的HTTPS响应处理

时间:2017-04-24 21:55:03

标签: python https azure-iot-hub

我在digi中使用嵌入式python(2.4.3)Connectport X4这里是使用HTTPS发布到Azure IoT Hub的代码:

import urllib, sys, datetime, time
import urllib2
iot_device_id = 'HTTP_Device'
iot_endpoint = 'https://winiothub.azure-devices.net/devices/' + iot_device_id + '/messages/events?api-version=2016-02-03'
sas_header = {'Authorization': 'SharedAccessSignature sr=winiothub.azure-devices.net%2Fdevices%2FHTTP_Device&sig=o7dndsA%2FJOnkzYRUhqAwMrQXVhOTpIJqJqILyGDdQAc%3D&se=1522414643'}
while True:
    #try:
        body_data = { 'gateway_serial': '123', 'readingvalue':'66.00', 'date': str(datetime.datetime.now())}
        iot_request = urllib2.Request(iot_endpoint, str(body_data), sas_header)
        resp = urllib2.urlopen(iot_request)
        contents = resp.read()
        resp.close()
        time.sleep(1)
    #except:
    #    print 'error'
    #    time.sleep(1)

代码实际上将消息发布到集线器,但是引发了以下错误:

Traceback (most recent call last):
  File "C:\Users\JeffreyBiesecker\documents\visual studio 2017\Projects\NewGateAzure\NewGateAzure\NewGateAzure2.py", line 14, in ?
    urllib2.urlopen(iot_request)
  File "C:\Python24\lib\urllib2.py", line 130, in urlopen
    return _opener.open(url, data)
  File "C:\Python24\lib\urllib2.py", line 364, in open
    response = meth(req, response)
  File "C:\Python24\lib\urllib2.py", line 471, in http_response
    response = self.parent.error(
  File "C:\Python24\lib\urllib2.py", line 402, in error
    return self._call_chain(*args)
  File "C:\Python24\lib\urllib2.py", line 337, in _call_chain
    result = func(*args)
  File "C:\Python24\lib\urllib2.py", line 480, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 204: No Content
Press any key to continue . . .

如果在嵌入式Digi网关中运行代码,或者在Visual Studio中使用2.4.3版本在Python中运行,则会出错。

1 个答案:

答案 0 :(得分:0)

urllib2.HttpError包含已收到的响应代码。因此,您可以捕获异常,测试204,并在这种情况下安全地继续。否则,您可以处理(或重新抛出)异常。

try:
    resp = urllib2.urlopen(iot_request)
except urllib2.HTTPError as e:
    if e.code == 204: pass
    else: raise