python - 类型错误 : Unicode-objects must be encoded before hashing in python for azure iot hub

标签 python azure raspberry-pi3 azure-iot-hub

我正在尝试将一些数据从 rasberry pi 上传到 azure iot hub,我遇到了这个问题,我需要在哪里设置编码/字符集?

我尝试过 data.encode('utf-8') 类似的东西,但不起作用。 可能有人问,请帮我解决这个特定的代码。 我正在关注this link .

def generate_sas_token():
    expiry=3600
    ttl = time.time() + expiry
    sign_key = "%s\n%d" % ((quote_plus(URI)), int(ttl))
    signature = b64encode(HMAC(b64decode(KEY), sign_key, sha256).digest())

    rawtoken = {
        'sr' :  URI,
        'sig': signature,
        'se' : str(int(ttl))
    }

    rawtoken['skn'] = POLICY

    return 'SharedAccessSignature ' + urlencode(rawtoken)

def send_message(token, message):
    url = 'https://{0}/devices/{1}/messages/events?api-version=2016-11-14'.format(URI, IOT_DEVICE_ID)
    headers = {
        "Content-Type": "application/json",
        "Authorization": token
    }
    data = json.dumps(message)
    print(data)
    #data.encode('utf-8')
    response = requests.post(url, data=data, headers=headers)

if __name__ == '__main__':
      # 2. Generate SAS Token
    token = generate_sas_token()

    # 3. Send Temperature to IoT Hub
    while True:
        #temp = read_temp() 
        message = { "temp": str("12") }
        send_message(token, message)
        time.sleep(1)

错误是

Traceback (most recent call last):
  File "/home/pi/python/test.py", line 45, in <module>
    token = generate_sas_token()
  File "/home/pi/python/test.py", line 20, in generate_sas_token
    signature = b64encode(HMAC(b64decode(KEY), sign_key, sha256).digest())
  File "/usr/lib/python3.5/hmac.py", line 84, in __init__
    self.update(msg)
  File "/usr/lib/python3.5/hmac.py", line 93, in update
    self.inner.update(msg)
TypeError: Unicode-objects must be encoded before hashing

最佳答案

该错误告诉您必须在创建 HMAC 对象之前进行编码。看来你要先解码它:

HMAC(b64decode(KEY), sign_key, sha256)

关于python - 类型错误 : Unicode-objects must be encoded before hashing in python for azure iot hub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55511450/

相关文章:

Azure 容器 - 与远程容器实例上的文件交互

azure - 使用 microsoft azure sql 数据库 v12 的 Visual Studio 构建错误 2015

tcp - 双向数据传输 - 串行到 Eth (Socat) (RPi)

python : cant open file 'hw.py' : [Errno 2] No such file or directory

python - 重载少于 python

python - 将行列表转换为 PySpark 数据框

Python如何删除带有黑名单不删除的项目列表

.net - Azure CDN 缓存,图像未立即更新?

ssl - 尝试创建 HTTPS 后运行 node-red-start "Error 140AB18F:SSL routines:SSL_CTX_use_certificate:ee key too small"

python - pyplot 图例用于按值着色的散点图