Ejemplo n.º 1
0
    def get(self, section_name):
        schema = _get_schema(self.schemas_dir, section_name, self.overrides)
        path = _path(self.settings_dir, section_name, _file_extension)
        raw = '{}'
        settings = dict()

        if os.path.exists(path):
            with open(path) as fid:
                # Attempt to load and parse the settings file.
                try:
                    raw = fid.read() or raw
                    settings = json.loads(json_minify(raw))
                except Exception as e:
                    message = 'Failed loading settings ({}): {}'
                    self.log.warn(message.format(section_name, str(e)))

        # Validate the parsed data against the schema.
        if len(settings):
            validator = Validator(schema)
            try:
                validator.validate(settings)
            except ValidationError as e:
                message = 'Failed validating settings ({}): {}'
                self.log.warn(message.format(section_name, str(e)))
                raw = '{}'

        # Send back the raw data to the client.
        resp = dict(id=section_name, raw=raw, schema=schema)

        self.finish(json.dumps(resp))
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
    def put(self, schema_name):
        overrides = self.overrides
        schemas_dir = self.schemas_dir
        settings_dir = self.settings_dir
        settings_error = 'No current settings directory'
        validation_error = 'Failed validating input: %s'

        if not settings_dir:
            raise web.HTTPError(500, settings_error)

        raw = self.request.body.strip().decode('utf-8')

        # Validate the data against the schema.
        schema, _ = _get_schema(schemas_dir,
                                schema_name,
                                overrides,
                                labextensions_path=self.labextensions_path)
        validator = Validator(schema)
        try:
            validator.validate(json5.loads(raw))
        except ValidationError as e:
            raise web.HTTPError(400, validation_error % str(e))

        # Write the raw data (comments included) to a file.
        path = _path(settings_dir, schema_name, True, SETTINGS_EXTENSION)
        with open(path, 'w', encoding='utf-8') as fid:
            fid.write(raw)

        self.set_status(204)
Ejemplo n.º 4
0
def _get_user_settings(settings_dir, schema_name, schema):
    """
    Returns a dictionary containing the raw user settings, the parsed user
    settings, a validation warning for a schema, and file times.
    """
    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'
    last_modified = None
    created = None

    if os.path.exists(path):
        stat = os.stat(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 dict(raw=raw, settings=settings, warning=warning)
Ejemplo n.º 5
0
    def put(self, schema_name):
        overrides = self.overrides
        schemas_dir = self.schemas_dir
        settings_dir = self.settings_dir
        settings_error = 'No current settings directory'
        invalid_json_error = 'Failed parsing JSON payload: %s'
        invalid_payload_format_error = 'Invalid format for JSON payload. Must be in the form {\'raw\': ...}'
        validation_error = 'Failed validating input: %s'

        if not settings_dir:
            raise web.HTTPError(500, settings_error)

        raw_payload = self.request.body.strip().decode(u'utf-8')
        try:
            raw_settings = json.loads(raw_payload)['raw']
            payload = json5.loads(raw_settings)
        except json.decoder.JSONDecodeError as e:
            raise web.HTTPError(400, invalid_json_error % str(e))
        except KeyError as e:
            raise web.HTTPError(400, invalid_payload_format_error)

        # Validate the data against the schema.
        schema = _get_schema(schemas_dir, schema_name, overrides)
        validator = Validator(schema)
        try:
            validator.validate(payload)
        except ValidationError as e:
            raise web.HTTPError(400, validation_error % str(e))

        # Write the raw data (comments included) to a file.
        path = _path(settings_dir, schema_name, True, SETTINGS_EXTENSION)
        with open(path, 'w') as fid:
            fid.write(raw_settings)

        self.set_status(204)
Ejemplo n.º 6
0
    def patch(self, section_name):
        if not self.settings_dir:
            raise web.HTTPError(404, "No current settings directory")

        path = os.path.join(self.schemas_dir, section_name + '.json')

        if not os.path.exists(path):
            raise web.HTTPError(404, "Schema not found for: %r" % section_name)

        data = self.get_json_body()  # Will raise 400 if content is not valid JSON

        # Validate the data against the schema.
        if Validator is not None:
            with open(path) as fid:
                schema = json.load(fid)
            validator = Validator(schema)
            try:
                validator.validate(data)
            except ValidationError as e:
                raise web.HTTPError(400, str(e))

        # Create the settings dir as needed.
        if not os.path.exists(self.settings_dir):
            os.makedirs(self.settings_dir)

        path = os.path.join(self.settings_dir, section_name + '.json')

        with open(path, 'w') as fid:
            json.dump(data, fid)

        self.set_status(204)
    def get(self, section_name):
        self.set_header("Content-Type", "application/json")

        schema = _get_schema(self.schemas_dir, section_name, self.overrides)
        path = _path(self.settings_dir, section_name, _file_extension)
        raw = "{}"
        settings = dict()

        if os.path.exists(path):
            with open(path) as fid:
                # Attempt to load and parse the settings file.
                try:
                    raw = fid.read() or raw
                    settings = json.loads(json_minify(raw))
                except Exception as e:
                    self.log.warn(str(e))

        # Validate the parsed data against the schema.
        if len(settings):
            validator = Validator(schema)
            try:
                validator.validate(settings)
            except ValidationError as e:
                self.log.warn(str(e))
                raw = "{}"

        # Send back the raw data to the client.
        resp = dict(id=section_name, raw=raw, schema=schema)

        self.finish(json.dumps(resp))
Ejemplo n.º 8
0
 def _validate_data(self, data: dict,
                    validator: jsonschema.Draft4Validator):
     try:
         validator.validate(data)
     except jsonschema.ValidationError as e:
         raise BadArguments(validation_error=e.message,
                            provider=self.provider_name,
                            data=data)
Ejemplo n.º 9
0
    def put(self, section_name):
        if not self.settings_dir:
            raise web.HTTPError(404, 'No current settings directory')

        raw = self.request.body.strip().decode(u'utf-8')

        # Validate the data against the schema.
        schema = _get_schema(self.schemas_dir, section_name, self.overrides)
        validator = Validator(schema)
        try:
            validator.validate(json.loads(json_minify(raw)))
        except ValidationError as e:
            raise web.HTTPError(400, str(e))

        # Write the raw data (comments included) to a file.
        path = _path(self.settings_dir, section_name, _file_extension, True)
        with open(path, 'w') as fid:
            fid.write(raw)

        self.set_status(204)
Ejemplo n.º 10
0
def save_settings(
    schemas_dir,
    settings_dir,
    schema_name,
    raw_settings,
    overrides,
    labextensions_path=None,
):
    """
    Save ``raw_settings`` settings for ``schema_name``.

    Parameters
    ----------
    schemas_dir: str
        Path to schemas.
    settings_dir: str
        Path to settings.
    schema_name str
        Schema name.
    raw_settings: str
        Raw serialized settings dictionary
    overrides: dict
        Settings overrides.
    labextensions_path: list, optional
        List of paths to federated labextensions containing their own schema files.
    """
    payload = json5.loads(raw_settings)

    # Validate the data against the schema.
    schema, _ = _get_schema(schemas_dir,
                            schema_name,
                            overrides,
                            labextensions_path=labextensions_path)
    validator = Validator(schema)
    validator.validate(payload)

    # Write the raw data (comments included) to a file.
    path = _path(settings_dir, schema_name, True, SETTINGS_EXTENSION)
    with open(path, "w", encoding="utf-8") as fid:
        fid.write(raw_settings)
Ejemplo n.º 11
0
    def get(self, section_name):
        self.set_header('Content-Type', "application/json")
        path = os.path.join(self.schemas_dir, section_name + ".json")

        if not os.path.exists(path):
            raise web.HTTPError(404, "Schema not found: %r" % section_name)
        with open(path) as fid:
            # Attempt to load the schema file.
            try:
                schema = json.load(fid)
            except Exception as e:
                name = section_name
                message = "Failed parsing schema ({}): {}".format(name, str(e))
                raise web.HTTPError(500, message)

        path = os.path.join(self.settings_dir, section_name + '.json')
        settings = dict()
        if os.path.exists(path):
            with open(path) as fid:
                # Attempt to load the settings file.
                try:
                    settings = json.load(fid)
                except Exception as e:
                    self.log.warn(str(e))

        # Validate the data against the schema.
        if Validator is not None and len(settings):
            validator = Validator(schema)
            try:
                validator.validate(settings)
            except ValidationError as e:
                self.log.warn(str(e))
                settings = dict()

        resp = dict(id=section_name, data=dict(user=settings), schema=schema)
        self.finish(json.dumps(resp))