【问题标题】:Traceback (most recent call last): PythonTraceback(最近一次调用最后一次):Python
【发布时间】:2017-03-29 06:48:10
【问题描述】:

当我尝试在 Eclipse 中运行我的 python 代码时,我收到了这个错误:

这是我的代码:

"""
Module Name:  deviceManager.py
Project:      IoTHubRestSample
Copyright (c) Microsoft Corporation.

Using [Device Indentities REST APIs](https://msdn.microsoft.com/en-us/library/azure/mt548489.aspx) to create a new device identity, retrieve a device identity, and list device identities.

This source is subject to the Microsoft Public License.
See http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
All other rights reserved.

THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
"""

import base64
import hmac
import hashlib
import time
import requests
import urllib

class DeviceManager:
    API_VERSION = '2016-02-03'
    TOKEN_VALID_SECS = 365 * 24 * 60 * 60
    TOKEN_FORMAT = 'SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s'

    def __init__(self, connectionString=None):
        if connectionString != None:
            iotHost, keyName, keyValue = [sub[sub.index('=') + 1:] for sub in connectionString.split(";")]
            self.iotHost = iotHost
            self.keyName = keyName
            self.keyValue = keyValue

    def _buildExpiryOn(self):
        return '%d' % (time.time() + self.TOKEN_VALID_SECS)

    def _buildSasToken(self):
        targetUri = self.iotHost.lower()
        expiryTime = self._buildExpiryOn()
        toSign = '%s\n%s' % (targetUri, expiryTime)
        key = base64.b64decode(self.keyValue.encode('utf-8'))
        signature = urllib.quote(
            base64.b64encode(
                hmac.HMAC(key, toSign.encode('utf-8'), hashlib.sha256).digest()
                )
        ).replace('/', '%2F')
        return self.TOKEN_FORMAT % (targetUri, signature, expiryTime, self.keyName)

    def createDeviceId(self, deviceId):
        sasToken = self._buildSasToken()
        url = 'https://%s/devices/%s?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION)
        body = '{deviceId: "%s"}' % deviceId
        r = requests.put(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken}, data=body)
        return r.text, r.status_code

    def retrieveDeviceId(self, deviceId):
        sasToken = self._buildSasToken()
        url = 'https://%s/devices/%s?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION)
        r = requests.get(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken})
        return r.text, r.status_code

    def listDeviceIds(self, top=None):
        if top == None:
            top = 1000
        sasToken = self._buildSasToken()
        url = 'https://%s/devices?top=%d&api-version=%s' % (self.iotHost, top, self.API_VERSION)
        r = requests.get(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken})
        return r.text, r.status_code

    def deleteDeviceId(self, deviceId):
        sasToken = self._buildSasToken()
        url = 'https://%s/devices/%s?api-version=%s' % (self.iotHost, deviceId, self.API_VERSION)
        r = requests.delete(url, headers={'Content-Type': 'application/json', 'Authorization': sasToken, 'If-Match': '*' }) 
        # If-Match Etag, but if * is used, no need to precise the Etag of the device. The Etag of the device can be seen in the header requests.text response 
        return r.text, r.status_code

if __name__ == '__main__':
    connectionString = 'HostName=<iot-hub-name>.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=<iothubowner-policy-key>'
    dm = DeviceManager(connectionString)
    deviceId='iotdevice1'
    print(dm.createDeviceId(deviceId))
    print(dm.retrieveDeviceId(deviceId))
    print(dm.listDeviceIds())

如何解决这个问题?

【问题讨论】:

  • 这与 java 有什么关系?从错误看来,您超出了请求库的重试次数限制。我建议你抓住异常并睡一段时间,例如5 秒后重试您的请求
  • 因为我是用eclipse来运行这段代码的。Python是和它集成的。我尝试调试但无法找到此错误。能否请您尝试查看随附的程序代码和错误截图并建议我解决方案?
  • 正如我所提到的,尝试捕获异常,将对第 55 行的调用放入 try-except 并休眠一段时间,然后再次调用相同的方法,看看它是否会运行通过
  • 欢迎来到 StackOverflow!请将您的代码直接添加到问题中(创建minimal reproducible example),而不是链接到网站。
  • 这个错误通常表示端点没有响应。你确定地址是正确的?它将重试多次,以防出现临时错误然后抛出此错误。堆栈交易中的主机名看起来很奇怪。看起来有点像你没有转义一些字符?

标签: python eclipse azure


【解决方案1】:

看来你的链接代码是我写的Azure代码示例,来自here,介绍在here。根据您的错误截图,我看到代码 connectionString = 'HostName=&lt;iot-hub-name&gt;.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=&lt;iothubowner-policy-key&gt;' 没有更改。如果您还没有创建 IoTHub,请按照官方教程 Create an IoT hub using the Azure portal 创建 IoTHub,并复制您的 IoT Hub 名称和密钥(如下)而不是 &lt;iot-hub-name&gt;&lt;iothubowner-policy-key&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-19
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多