This commit is contained in:
Paulus Schoutsen 2016-05-16 00:25:47 -07:00
parent 8fe2654862
commit 9aa9e57890
6 changed files with 21 additions and 58 deletions

View File

@ -15,7 +15,7 @@ from homeassistant.const import (
HTTP_BAD_REQUEST, HTTP_CREATED, HTTP_NOT_FOUND, HTTP_BAD_REQUEST, HTTP_CREATED, HTTP_NOT_FOUND,
HTTP_UNPROCESSABLE_ENTITY, MATCH_ALL, URL_API, URL_API_COMPONENTS, HTTP_UNPROCESSABLE_ENTITY, MATCH_ALL, URL_API, URL_API_COMPONENTS,
URL_API_CONFIG, URL_API_DISCOVERY_INFO, URL_API_ERROR_LOG, URL_API_CONFIG, URL_API_DISCOVERY_INFO, URL_API_ERROR_LOG,
URL_API_EVENT_FORWARD, URL_API_EVENTS, URL_API_LOG_OUT, URL_API_SERVICES, URL_API_EVENT_FORWARD, URL_API_EVENTS, URL_API_SERVICES,
URL_API_STATES, URL_API_STATES_ENTITY, URL_API_STREAM, URL_API_TEMPLATE, URL_API_STATES, URL_API_STATES_ENTITY, URL_API_STREAM, URL_API_TEMPLATE,
__version__) __version__)
from homeassistant.exceptions import TemplateError from homeassistant.exceptions import TemplateError
@ -48,7 +48,6 @@ def setup(hass, config):
hass.wsgi.register_view(APIEventForwardingView) hass.wsgi.register_view(APIEventForwardingView)
hass.wsgi.register_view(APIComponentsView) hass.wsgi.register_view(APIComponentsView)
hass.wsgi.register_view(APIErrorLogView) hass.wsgi.register_view(APIErrorLogView)
hass.wsgi.register_view(APILogOutView)
hass.wsgi.register_view(APITemplateView) hass.wsgi.register_view(APITemplateView)
return True return True
@ -129,7 +128,7 @@ class APIEventStream(HomeAssistantView):
self.hass.bus.listen(MATCH_ALL, thread_forward_events) self.hass.bus.listen(MATCH_ALL, thread_forward_events)
attached_ping = track_utc_time_change( attached_ping = track_utc_time_change(
self.hass, thread_ping, second=range(0, 60, 3)) #(0, 30)) self.hass, thread_ping, second=(0, 30))
_LOGGER.debug('STREAM %s ATTACHED', id(stop_obj)) _LOGGER.debug('STREAM %s ATTACHED', id(stop_obj))
@ -401,18 +400,6 @@ class APIErrorLogView(HomeAssistantView):
return self.file(request, self.hass.config.path(ERROR_LOG_FILENAME)) return self.file(request, self.hass.config.path(ERROR_LOG_FILENAME))
class APILogOutView(HomeAssistantView):
"""View to handle Log Out requests."""
url = URL_API_LOG_OUT
name = "api:log-out"
def post(self, request):
"""Handle log out."""
# TODO kill session
return {}
class APITemplateView(HomeAssistantView): class APITemplateView(HomeAssistantView):
"""View to handle requests.""" """View to handle requests."""

View File

@ -100,6 +100,8 @@ class IndexView(HomeAssistantView):
template = self.templates.get_template('index.html') template = self.templates.get_template('index.html')
# pylint is wrong
# pylint: disable=no-member
resp = template.render(app_url=app_url, auth=auth, resp = template.render(app_url=app_url, auth=auth,
icons=mdi_version.VERSION) icons=mdi_version.VERSION)

View File

@ -70,7 +70,8 @@ def setup(hass, config):
def request_class(): def request_class():
"""Generate request class. """Generate request class.
Done in method because of imports.""" Done in method because of imports.
"""
from werkzeug.exceptions import BadRequest from werkzeug.exceptions import BadRequest
from werkzeug.wrappers import BaseRequest, AcceptMixin from werkzeug.wrappers import BaseRequest, AcceptMixin
from werkzeug.utils import cached_property from werkzeug.utils import cached_property
@ -100,6 +101,7 @@ def routing_map(hass):
class EntityValidator(BaseConverter): class EntityValidator(BaseConverter):
"""Validate entity_id in urls.""" """Validate entity_id in urls."""
regex = r"(\w+)\.(\w+)" regex = r"(\w+)\.(\w+)"
def __init__(self, url_map, exist=True, domain=None): def __init__(self, url_map, exist=True, domain=None):
@ -259,17 +261,16 @@ class HomeAssistantWSGI(object):
return self.views[endpoint].handle_request(request, **values) return self.views[endpoint].handle_request(request, **values)
except RequestRedirect as ex: except RequestRedirect as ex:
return ex return ex
except BadRequest as ex: except (BadRequest, NotFound, MethodNotAllowed,
return self._handle_error(request, str(ex), 400) Unauthorized) as ex:
except NotFound as ex: resp = ex.get_response(request.environ)
return self._handle_error(request, str(ex), 404) if request.accept_mimetypes.accept_json:
except MethodNotAllowed as ex: resp.data = json.dumps({
return self._handle_error(request, str(ex), 405) "result": "error",
except Unauthorized as ex: "message": str(ex),
return self._handle_error(request, str(ex), 401) })
# TODO This long chain of except blocks is silly. _handle_error should resp.mimetype = "application/json"
# just take the exception as an argument and parse the status code return resp
# itself
def base_app(self, environ, start_response): def base_app(self, environ, start_response):
"""WSGI Handler of requests to base app.""" """WSGI Handler of requests to base app."""
@ -288,19 +289,6 @@ class HomeAssistantWSGI(object):
environ['PATH_INFO'] = "{}.{}".format(*fingerprinted.groups()) environ['PATH_INFO'] = "{}.{}".format(*fingerprinted.groups())
return app(environ, start_response) return app(environ, start_response)
def _handle_error(self, request, message, status):
"""Handle a WSGI request error."""
from werkzeug.wrappers import Response
if request.accept_mimetypes.accept_json:
message = json.dumps({
"result": "error",
"message": message,
})
mimetype = "application/json"
else:
mimetype = "text/plain"
return Response(message, status=status, mimetype=mimetype)
class HomeAssistantView(object): class HomeAssistantView(object):
"""Base view for all views.""" """Base view for all views."""
@ -339,8 +327,6 @@ class HomeAssistantView(object):
except AttributeError: except AttributeError:
raise MethodNotAllowed raise MethodNotAllowed
# TODO: session support + uncomment session test
# Auth code verbose on purpose # Auth code verbose on purpose
authenticated = False authenticated = False

View File

@ -2,8 +2,8 @@
def spawn(hub, func, *args, **kwargs): def spawn(hub, func, *args, **kwargs):
"""Spawns a function on specified hub.""" """Spawn a function on specified hub."""
import eventlet import eventlet
g = eventlet.greenthread.GreenThread(hub.greenlet) gthread = eventlet.greenthread.GreenThread(hub.greenlet)
hub.schedule_call_global(0, g.switch, func, args, kwargs) hub.schedule_call_global(0, gthread.switch, func, args, kwargs)
return g return gthread

View File

@ -274,9 +274,6 @@ python-nmap==0.6.0
# homeassistant.components.notify.pushover # homeassistant.components.notify.pushover
python-pushover==0.2 python-pushover==0.2
# homeassistant.components.socket_io
python-socketio==1.3
# homeassistant.components.statsd # homeassistant.components.statsd
python-statsd==1.7.2 python-statsd==1.7.2

View File

@ -88,15 +88,6 @@ class TestAPI(unittest.TestCase):
self.assertEqual(200, req.status_code) self.assertEqual(200, req.status_code)
# def test_access_via_session(self):
# """Test access wia session."""
# session = requests.Session()
# req = session.get(_url(const.URL_API), headers=HA_HEADERS)
# self.assertEqual(200, req.status_code)
# req = session.get(_url(const.URL_API))
# self.assertEqual(200, req.status_code)
def test_api_list_state_entities(self): def test_api_list_state_entities(self):
"""Test if the debug interface allows us to list state entities.""" """Test if the debug interface allows us to list state entities."""
req = requests.get(_url(const.URL_API_STATES), req = requests.get(_url(const.URL_API_STATES),