我尝试发送JSON消息,但我发送的设备要求API密钥使用base64进行编码。这一切都被绑定到一个名为Home Assistant
的项目中这是我的代码:
import logging
import requests
import base64
import voluptuous as vol
from homeassistant.components.notify import ATTR_MESSAGE, \
PLATFORM_SCHEMA, BaseNotificationService
from homeassistant.const import CONF_API_KEY, CONF_HOST
import homeassistant.helpers.config_validation as cv
api_key = CONF_API_KEY
NOTE_URL = 'http://' + CONF_HOST + ':8080/api/v2/device/notifications'
encoded_api = base64.b64encode(api_key.encode('ascii'))
headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Basic ' + encoded_api,
'Cache-Control': 'no-cache',
}
data = '{"priority": "warning", "icon_type": "none", "model": \
{"frames": [{"icon": "i3579", "text": ' + ATTR_MESSAGE + '}], \
"sound": {"category": "notifications", "id": "positive4"}}}'
requests.post(NOTE_URL, headers=headers, data=data)
启动时,这会在TypeError: Can't convert 'bytes' object to str implicitly
行上显示'Authorization': 'Basic ' + encoded_api,
错误。
我尝试用`encoded_api =(api_key).decode(" UTF-8")隐式调用它,我尝试过io.StringIO,其他人无济于事。
有什么建议吗?
感谢。