Refactored to new global json saving and loading (#10677)

* Refactored to new global json saving and loading

* Fixed emulated_hue tests

* Removed unnecassary error handling

* Added missing newline

* Remove unused imports

* Fixed linting error

* Moved _load_json wrapper out of the config class
This commit is contained in:
Markus Nigbur authored and Paulus Schoutsen committed 2017-11-19 19:47:55 -08:00
1 parent 7695ca2c8b
commit a83e741dc7
15 files changed
+73 -348

No files matched your search

+7 -34
View File
@@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.fitbit/
"""
import os
import json
import logging
import datetime
import time
@@ -19,6 +18,8 @@ from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.icon import icon_for_battery_level
import homeassistant.helpers.config_validation as cv
from homeassistant.util.json import load_json, save_json
REQUIREMENTS = ['fitbit==0.3.0']
@@ -147,31 +148,6 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
def config_from_file(filename, config=None):
"""Small configuration file management function."""
if config:
# We"re writing configuration
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(config))
except IOError as error:
_LOGGER.error("Saving config file failed: %s", error)
return False
return config
else:
# We"re reading config
if os.path.isfile(filename):
try:
with open(filename, 'r') as fdesc:
return json.loads(fdesc.read())
except IOError as error:
_LOGGER.error("Reading config file failed: %s", error)
# This won"t work yet
return False
else:
return {}
def request_app_setup(hass, config, add_devices, config_path,
discovery_info=None):
"""Assist user with configuring the Fitbit dev application."""
@@ -182,7 +158,7 @@ def request_app_setup(hass, config, add_devices, config_path,
"""Handle configuration updates."""
config_path = hass.config.path(FITBIT_CONFIG_FILE)
if os.path.isfile(config_path):
config_file = config_from_file(config_path)
config_file = load_json(config_path)
if config_file == DEFAULT_CONFIG:
error_msg = ("You didn't correctly modify fitbit.conf",
" please try again")
@@ -242,13 +218,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Fitbit sensor."""
config_path = hass.config.path(FITBIT_CONFIG_FILE)
if os.path.isfile(config_path):
config_file = config_from_file(config_path)
config_file = load_json(config_path)
if config_file == DEFAULT_CONFIG:
request_app_setup(
hass, config, add_devices, config_path, discovery_info=None)
return False
else:
config_file = config_from_file(config_path, DEFAULT_CONFIG)
config_file = save_json(config_path, DEFAULT_CONFIG)
request_app_setup(
hass, config, add_devices, config_path, discovery_info=None)
return False
@@ -384,9 +360,7 @@ class FitbitAuthCallbackView(HomeAssistantView):
ATTR_CLIENT_SECRET: self.oauth.client_secret,
ATTR_LAST_SAVED_AT: int(time.time())
}
if not config_from_file(hass.config.path(FITBIT_CONFIG_FILE),
config_contents):
_LOGGER.error("Failed to save config file")
save_json(hass.config.path(FITBIT_CONFIG_FILE), config_contents)
hass.async_add_job(setup_platform, hass, self.config, self.add_devices)
@@ -513,5 +487,4 @@ class FitbitSensor(Entity):
ATTR_CLIENT_SECRET: self.client.client.client_secret,
ATTR_LAST_SAVED_AT: int(time.time())
}
if not config_from_file(self.config_path, config_contents):
_LOGGER.error("Failed to save config file")
save_json(self.config_path, config_contents)
+4 -24
View File
@@ -4,9 +4,7 @@ Support for monitoring an SABnzbd NZB client.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.sabnzbd/
"""
import os
import logging
import json
from datetime import timedelta
import voluptuous as vol
@@ -17,6 +15,7 @@ from homeassistant.const import (
CONF_SSL)
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
from homeassistant.util.json import load_json, save_json
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['https://github.com/jamespcole/home-assistant-nzb-clients/'
@@ -104,9 +103,9 @@ def request_configuration(host, name, hass, config, add_devices, sab_api):
def success():
"""Set up was successful."""
conf = _read_config(hass)
conf = load_json(hass.config.path(CONFIG_FILE))
conf[host] = {'api_key': api_key}
_write_config(hass, conf)
save_json(hass.config.path(CONFIG_FILE), conf)
req_config = _CONFIGURING.pop(host)
hass.async_add_job(configurator.request_done, req_config)
@@ -144,7 +143,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
api_key = config.get(CONF_API_KEY)
if not api_key:
conf = _read_config(hass)
conf = load_json(hass.config.path(CONFIG_FILE))
if conf.get(base_url, {}).get('api_key'):
api_key = conf[base_url]['api_key']
@@ -214,22 +213,3 @@ class SabnzbdSensor(Entity):
self._state = self.sabnzb_client.queue.get('diskspace1')
else:
self._state = 'Unknown'
def _read_config(hass):
"""Read SABnzbd config."""
path = hass.config.path(CONFIG_FILE)
if not os.path.isfile(path):
return {}
with open(path) as f_handle:
# Guard against empty file
return json.loads(f_handle.read() or '{}')
def _write_config(hass, config):
"""Write SABnzbd config."""
data = json.dumps(config)
with open(hass.config.path(CONFIG_FILE), 'w', encoding='utf-8') as outfile:
outfile.write(data)