Skip to content

Commit

Permalink
Expose settings API to other handlers.
Browse files Browse the repository at this point in the history
  • Loading branch information
goanpeca committed Jul 4, 2020
1 parent 0d8fb81 commit a7a4c05
Showing 1 changed file with 112 additions and 68 deletions.
180 changes: 112 additions & 68 deletions jupyterlab_server/settings_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,39 +49,6 @@ def _get_schema(schemas_dir, schema_name, overrides):
return schema


def _get_settings(settings_dir, schema_name, schema):
"""
Returns a tuple containing the raw user settings, the parsed user
settings, and a validation warning for a schema.
"""

path = _path(settings_dir, schema_name, False, SETTINGS_EXTENSION)
raw = '{}'
settings = dict()
warning = ''
validation_warning = 'Failed validating settings (%s): %s'
parse_error = 'Failed loading settings (%s): %s'

if os.path.exists(path):
with open(path) as fid:
try: # to load and parse the settings file.
raw = fid.read() or raw
settings = json5.loads(raw)
except Exception as e:
raise web.HTTPError(500, parse_error % (schema_name, str(e)))

# Validate the parsed data against the schema.
if len(settings):
validator = Validator(schema)
try:
validator.validate(settings)
except ValidationError as e:
warning = validation_warning % (schema_name, str(e))
raw = '{}'

return (raw, settings, warning)


def _get_version(schemas_dir, schema_name):
"""Returns the package version for a given schema or 'N/A' if not found."""

Expand Down Expand Up @@ -185,51 +152,128 @@ def _path(root_dir, schema_name, make_dirs=False, extension='.json'):
return path


class SettingsHandler(APIHandler):
def _load_overrides(app_settings_dir):
"""Load overrides settings from `app_settings_dir`."""
overrides_path = os.path.join(app_settings_dir, 'overrides.json')
if os.path.exists(overrides_path):
with open(overrides_path) as fid:
try:
overrides = json.load(fid)
error = ""
except Exception as e:
overrides = {}
error = e

def initialize(self, app_settings_dir, schemas_dir, settings_dir):
self.overrides = dict()
self.schemas_dir = schemas_dir
self.settings_dir = settings_dir
return overrides, error

overrides_path = os.path.join(app_settings_dir, 'overrides.json')
overrides_warning = 'Failed loading overrides: %s'

if os.path.exists(overrides_path):
with open(overrides_path) as fid:
try:
self.overrides = json.load(fid)
except Exception as e:
self.log.warn(overrides_warning % str(e))
def _get_settings(settings_dir, schema_name, schema):
"""
Returns a tuple containing the raw user settings, the parsed user
settings, and a validation warning for a schema.
"""
path = _path(settings_dir, schema_name, False, SETTINGS_EXTENSION)
raw = '{}'
settings = {}
warning = ''
validation_warning = 'Failed validating settings (%s): %s'
parse_error = 'Failed loading settings (%s): %s'

@web.authenticated
def get(self, schema_name=''):
overrides = self.overrides
schemas_dir = self.schemas_dir
settings_dir = self.settings_dir
if os.path.exists(path):
with open(path) as fid:
try: # to load and parse the settings file.
raw = fid.read() or raw
settings = json5.loads(raw)
except Exception as e:
raise web.HTTPError(500, parse_error % (schema_name, str(e)))

if not schema_name:
settings_list, warnings = _list_settings(
schemas_dir, settings_dir, overrides)
if warnings:
self.log.warn('\n'.join(warnings))
return self.finish(json.dumps(dict(settings=settings_list)))
# Validate the parsed data against the schema.
if len(settings):
validator = Validator(schema)
try:
validator.validate(settings)
except ValidationError as e:
warning = validation_warning % (schema_name, str(e))
raw = '{}'

return (raw, settings, warning)


def get_settings(app_settings_dir, schemas_dir, settings_dir, schema_name="", overrides=None):
"""
Get setttings.
Parameters
----------
app_settings_dir:
Path to applications settings.
schemas_dir: str
Path to schemas.
settings_dir:
Path to settings.
schema_name str, optional
Schema name. Default is None.
overrides: dict, optional
Settings overrides. If not provided, the overrides will be loaded
from the `app_settings_dir`. Default is None.
Returns
-------
tuple
The first item is a dictionary with a list of setting if no `schema_name`
was provided, otherwise it is a dictionary with id, raw, scheme, settings
and version keys. The second item is a list of warnings.
"""
if overrides is None:
overrides, _error = _load_overrides(app_settings_dir)

if schema_name == "":
settings_list, warnings = _list_settings(schemas_dir, settings_dir, overrides)
result = {
"settings": settings_list,
}
else:
schema = _get_schema(schemas_dir, schema_name, overrides)
raw, settings, warning = _get_settings(
settings_dir, schema_name, schema)
raw, settings, _warning = _get_settings(settings_dir, schema_name, schema)
version = _get_version(schemas_dir, schema_name)
result = {
"id": schema_name,
"raw": raw,
"schema": schema,
"settings": settings,
"version": version,
}
warnings = [_warning]

if warning:
self.log.warn(warning)
return result, warnings

self.finish(json.dumps(dict(
id=schema_name,
raw=raw,
schema=schema,
settings=settings,
version=version
)))

class SettingsHandler(APIHandler):

def initialize(self, app_settings_dir, schemas_dir, settings_dir):
self.overrides, error = _load_overrides(app_settings_dir)
self.app_settings_dir = app_settings_dir
self.schemas_dir = schemas_dir
self.settings_dir = settings_dir

if error:
overrides_warning = 'Failed loading overrides: %s'
self.log.warn(overrides_warning % str(error))

@web.authenticated
def get(self, schema_name=""):
result, warnings = get_settings(
self.app_settings_dir,
self.schemas_dir,
self.settings_dir,
schema_name=schema_name,
overrides=self.overrides,
)

if warnings:
self.log.warn('\n'.join(warnings))

return self.finish(json.dumps(result))

@web.authenticated
def put(self, schema_name):
Expand Down

0 comments on commit a7a4c05

Please sign in to comment.