【问题标题】:urllib2 does not handle http NO_CONTENT (204) as a successful HTTPS responseurllib2 不处理 http NO_CONTENT (204) 作为成功的 HTTPS 响应
【发布时间】:2017-04-24 21:55:02
【问题描述】:

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

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 运行,我会收到错误。

【问题讨论】:

    标签: python https azure-iot-hub


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我一定会添加此代码。这是个好主意,我想知道为什么 204 在 python 2.4 中是一个错误,但在 2.7 中它没有报告为错误。我在 Visual Studio 中对此进行了测试。感谢大家的帮助!!!!
    • 我不知道为什么这是一个错误,这似乎不直观 - 在调试器中单步执行 urllib2 可能在这里有用。
    猜你喜欢
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2012-10-24
    • 2014-10-05
    • 1970-01-01
    相关资源
    最近更新 更多