exposed content_type in rest_command (#7101)

* exposed content_type in rest_command, which allows for manually specifying the content_type for more-strict api endpoints

* fixed up column length

Length was 86 chars, and it needed to be 79

* double import of HTTP_HEADER_CONTENT_TYPE

Removed the accidental double-import of HTTP_HEADER_CONTENT_TYPE

* moved rest_command-specific config value into component

* if no content_type, default to None

* unit test

* newline

* unused CONTENT_TYPE_TEXT_PLAIN

* removed the http-agnostic abstraction hass provided in favor of aiohttps hdrs constant
This commit is contained in:
Mike Megally 2017-04-18 02:50:43 -07:00 committed by Pascal Vizeli
parent 43799b8fee
commit 226066eafd
2 changed files with 30 additions and 1 deletions

View file

@ -8,6 +8,7 @@ import asyncio
import logging
import aiohttp
from aiohttp import hdrs
import async_timeout
import voluptuous as vol
@ -31,6 +32,8 @@ SUPPORT_REST_METHODS = [
'delete',
]
CONF_CONTENT_TYPE = 'content_type'
COMMAND_SCHEMA = vol.Schema({
vol.Required(CONF_URL): cv.template,
vol.Optional(CONF_METHOD, default=DEFAULT_METHOD):
@ -39,6 +42,7 @@ COMMAND_SCHEMA = vol.Schema({
vol.Inclusive(CONF_PASSWORD, 'authentication'): cv.string,
vol.Optional(CONF_PAYLOAD): cv.template,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): vol.Coerce(int),
vol.Optional(CONF_CONTENT_TYPE): cv.string
})
CONFIG_SCHEMA = vol.Schema({
@ -72,6 +76,11 @@ def async_setup(hass, config):
template_payload = command_config[CONF_PAYLOAD]
template_payload.hass = hass
headers = None
if CONF_CONTENT_TYPE in command_config:
content_type = command_config[CONF_CONTENT_TYPE]
headers = {hdrs.CONTENT_TYPE: content_type}
@asyncio.coroutine
def async_service_handler(service):
"""Execute a shell command service."""
@ -86,7 +95,8 @@ def async_setup(hass, config):
request = yield from getattr(websession, method)(
template_url.async_render(variables=service.data),
data=payload,
auth=auth
auth=auth,
headers=headers
)
if request.status < 400:

View file

@ -221,3 +221,22 @@ class TestRestCommandComponent(object):
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == b'data'
def test_rest_command_content_type(self, aioclient_mock):
"""Call a rest command with a content type."""
data = {
'payload': 'item',
'content_type': 'text/plain'
}
self.config[rc.DOMAIN]['post_test'].update(data)
with assert_setup_component(4):
setup_component(self.hass, rc.DOMAIN, self.config)
aioclient_mock.post(self.url, content=b'success')
self.hass.services.call(rc.DOMAIN, 'post_test', {})
self.hass.block_till_done()
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == b'item'