mirror of
https://github.com/home-assistant/core.git
synced 2025-07-09 22:37:11 +00:00
Extracted json saving and loading (#10216)
This commit is contained in:
parent
85f30b893e
commit
4e8723f345
@ -6,7 +6,6 @@ https://home-assistant.io/components/media_player.plex/
|
|||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
@ -22,6 +21,7 @@ from homeassistant.const import (
|
|||||||
DEVICE_DEFAULT_NAME, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING)
|
DEVICE_DEFAULT_NAME, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING)
|
||||||
from homeassistant.helpers import config_validation as cv
|
from homeassistant.helpers import config_validation as cv
|
||||||
from homeassistant.helpers.event import track_utc_time_change
|
from homeassistant.helpers.event import track_utc_time_change
|
||||||
|
from homeassistant.util.json import load_json, save_json
|
||||||
|
|
||||||
REQUIREMENTS = ['plexapi==3.0.3']
|
REQUIREMENTS = ['plexapi==3.0.3']
|
||||||
|
|
||||||
@ -48,35 +48,10 @@ 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 True
|
|
||||||
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 setup_platform(hass, config, add_devices_callback, discovery_info=None):
|
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
|
||||||
"""Set up the Plex platform."""
|
"""Set up the Plex platform."""
|
||||||
# get config from plex.conf
|
# get config from plex.conf
|
||||||
file_config = config_from_file(hass.config.path(PLEX_CONFIG_FILE))
|
file_config = load_json(hass.config.path(PLEX_CONFIG_FILE))
|
||||||
|
|
||||||
if file_config:
|
if file_config:
|
||||||
# Setup a configured PlexServer
|
# Setup a configured PlexServer
|
||||||
@ -146,7 +121,7 @@ def setup_plexserver(
|
|||||||
_LOGGER.info("Discovery configuration done")
|
_LOGGER.info("Discovery configuration done")
|
||||||
|
|
||||||
# Save config
|
# Save config
|
||||||
if not config_from_file(
|
if not save_json(
|
||||||
hass.config.path(PLEX_CONFIG_FILE), {host: {
|
hass.config.path(PLEX_CONFIG_FILE), {host: {
|
||||||
'token': token,
|
'token': token,
|
||||||
'ssl': has_ssl,
|
'ssl': has_ssl,
|
||||||
|
50
homeassistant/util/json.py
Normal file
50
homeassistant/util/json.py
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
"""JSON utility functions."""
|
||||||
|
import logging
|
||||||
|
from typing import Union, List, Dict
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def load_json(filename: str) -> Union[List, Dict]:
|
||||||
|
"""Load JSON data from a file and return as dict or list.
|
||||||
|
|
||||||
|
Defaults to returning empty dict if file is not found.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
with open(filename, encoding='utf-8') as fdesc:
|
||||||
|
return json.loads(fdesc.read())
|
||||||
|
except FileNotFoundError:
|
||||||
|
# This is not a fatal error
|
||||||
|
_LOGGER.debug('JSON file not found: %s', filename)
|
||||||
|
except ValueError as error:
|
||||||
|
_LOGGER.exception('Could not parse JSON content: %s', filename)
|
||||||
|
raise HomeAssistantError(error)
|
||||||
|
except OSError as error:
|
||||||
|
_LOGGER.exception('JSON file reading failed: %s', filename)
|
||||||
|
raise HomeAssistantError(error)
|
||||||
|
return {} # (also evaluates to False)
|
||||||
|
|
||||||
|
|
||||||
|
def save_json(filename: str, config: Union[List, Dict]):
|
||||||
|
"""Save JSON data to a file.
|
||||||
|
|
||||||
|
Returns True on success.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
data = json.dumps(config, sort_keys=True, indent=4)
|
||||||
|
with open(filename, 'w', encoding='utf-8') as fdesc:
|
||||||
|
fdesc.write(data)
|
||||||
|
return True
|
||||||
|
except TypeError as error:
|
||||||
|
_LOGGER.exception('Failed to serialize to JSON: %s',
|
||||||
|
filename)
|
||||||
|
raise HomeAssistantError(error)
|
||||||
|
except OSError as error:
|
||||||
|
_LOGGER.exception('Saving JSON file failed: %s',
|
||||||
|
filename)
|
||||||
|
raise HomeAssistantError(error)
|
||||||
|
return False
|
Loading…
x
Reference in New Issue
Block a user