Python oslo_serialization.jsonutils.load() Examples

The following are 22 code examples of oslo_serialization.jsonutils.load(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oslo_serialization.jsonutils , or try the search function .
Example #1
Source File: patches.py    From designate with Apache License 2.0 6 votes vote down vote up
def body_dict(self):
        """
        Returns the body content as a dictionary, deserializing per the
        Content-Type header.

        We add this method to ease future XML support, so the main code
        is not hardcoded to call pecans "request.json" method.
        """
        if self.content_type not in JSON_TYPES:
            raise exceptions.UnsupportedContentType(
                'Content-type must be application/json')

        try:
            json_dict = jsonutils.load(self.body_file)
            if json_dict is None:
                # NOTE(kiall): Somehow, json.load(fp) is returning None.
                raise exceptions.EmptyRequestBody('Request Body is empty')
            return json_dict
        except ValueError as e:
            if not self.body:
                raise exceptions.EmptyRequestBody('Request Body is empty')
            else:
                raise exceptions.InvalidJson(six.text_type(e)) 
Example #2
Source File: scheduler_options.py    From manila with Apache License 2.0 6 votes vote down vote up
def get_configuration(self, filename=None):
        """Check the json file for changes and load it if needed."""
        if not filename:
            filename = CONF.scheduler_json_config_location
        if not filename:
            return self.data
        if self.last_checked:
            now = self._get_time_now()
            if now - self.last_checked < datetime.timedelta(minutes=5):
                return self.data

        last_modified = self._get_file_timestamp(filename)
        if (not last_modified or not self.last_modified or
                last_modified > self.last_modified):
            self.data = self._load_file(self._get_file_handle(filename))
            self.last_modified = last_modified
        if not self.data:
            self.data = {}

        return self.data 
Example #3
Source File: test_glance_plugins.py    From searchlight with Apache License 2.0 5 votes vote down vote up
def _get_glance_image_owner_and_count(self):
        with open(generate_load_data.IMAGES_FILE, "r+b") as file:
            images_data = jsonutils.load(file)
        if len(images_data) > 0:
            return len(images_data), images_data[0]['owner'] 
Example #4
Source File: test_nova_notifications.py    From watcher with Apache License 2.0 5 votes vote down vote up
def load_message(filename):
        cwd = os.path.abspath(os.path.dirname(__file__))
        data_folder = os.path.join(cwd, "data")

        with open(os.path.join(data_folder, filename), 'rb') as json_file:
            json_data = jsonutils.load(json_file)

        return json_data 
Example #5
Source File: test_cinder_notifications.py    From watcher with Apache License 2.0 5 votes vote down vote up
def load_message(filename):
        cwd = os.path.abspath(os.path.dirname(__file__))
        data_folder = os.path.join(cwd, "data")

        with open(os.path.join(data_folder, filename), 'rb') as json_file:
            json_data = jsonutils.load(json_file)

        return json_data 
Example #6
Source File: test_notifications.py    From watcher with Apache License 2.0 5 votes vote down vote up
def load_message(self, filename):
        cwd = os.path.abspath(os.path.dirname(__file__))
        data_folder = os.path.join(cwd, "data")

        with open(os.path.join(data_folder, filename), 'rb') as json_file:
            json_data = jsonutils.load(json_file)

        return json_data 
Example #7
Source File: datapath.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def load_datapath_from_file_stream(stream):
    dp_allocs_dict = jsonutils.load(stream)
    return load_datapath_from_dict(dp_allocs_dict) 
Example #8
Source File: datapath.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def _get_app_class(self, app_type):
        """Get an application class (Python class) by app name"""
        mgr = stevedore.NamedExtensionManager(
            'dragonflow.controller.apps',
            [app_type],
            invoke_on_load=False,
        )
        for ext in mgr:
            return ext.plugin
        else:
            raise RuntimeError(_('Failed to load app {0}').format(app_type)) 
Example #9
Source File: json_ref.py    From masakari with Apache License 2.0 5 votes vote down vote up
def _resolve_ref(ref, base_path):
    file_path, _, json_path = ref.partition('#')
    if json_path:
        raise NotImplementedError('JSON refs with JSON path after the "#" is '
                                  'not yet supported')

    path = os.path.join(base_path, file_path)
    # binary mode is needed due to bug/1515231
    with open(path, 'r+b') as f:
        ref_value = jsonutils.load(f)
        base_path = os.path.dirname(path)
        res = resolve_refs(ref_value, base_path)
        return res 
Example #10
Source File: scheduler_options.py    From manila with Apache License 2.0 5 votes vote down vote up
def _load_file(self, handle):
        """Decode the JSON file. Broken out for testing."""
        try:
            return jsonutils.load(handle)
        except ValueError:
            LOG.exception("Could not decode scheduler options.")
            return {} 
Example #11
Source File: mock_glance_pyclient.py    From searchlight with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        # Load Images from file
        self._images = []
        with open(generate_load_data.IMAGES_FILE, "r+b") as file:
            image_data = jsonutils.load(file)
        for image in image_data:
            fake_image = FakeImage(**image)
            self._images.append(fake_image)
        self.images = FakeImages(self._images)

        # Load Images members from file
        self._images_members_dict = dict()
        self._image_members_list = []
        with open(generate_load_data.IMAGE_MEMBERS_FILE, "r+b") as file:
            image_members_data = jsonutils.load(file)
        for image_id, image_members in image_members_data.items():
            for image_member in image_members:
                fake_image_member = FakeImageMember(**image_member)
                self._image_members_list.append(fake_image_member)
            self._images_members_dict[image_id] = self._image_members_list
        self.image_members = FakeImageMembers(self._images_members_dict)

        # Load Metadef namespaces from file
        self._metadefs_namespace = []
        self.metadefs_namespace = []
        with open(generate_load_data.METADEFS_FILE, "r+b") as file:
            metadefs_namespace_data = jsonutils.load(file)
        for metadef_namespace in metadefs_namespace_data:
            fake_namespace = FakeNamespace(**metadef_namespace)
            self._metadefs_namespace.append(fake_namespace)
        self.metadefs_namespace = FakeNamespaces(self._metadefs_namespace) 
Example #12
Source File: test_glance_plugins.py    From searchlight with Apache License 2.0 5 votes vote down vote up
def _get_glance_metadefs_owner_and_count(self):
        with open(generate_load_data.METADEFS_FILE, "r+b") as file:
            metadefs_data = jsonutils.load(file)
        if len(metadefs_data) > 0:
            return len(metadefs_data), metadefs_data[0]['owner'] 
Example #13
Source File: cni.py    From zun with Apache License 2.0 5 votes vote down vote up
def main():
    d = jsonutils.load(sys.stdin.buffer)
    cni_conf = utils.CNIConfig(d)
    args = (['--config-file', cni_conf.zun_conf] if 'zun_conf' in d
            else [])

    try:
        if cni_conf.debug:
            args.append('-d')
    except AttributeError:
        pass
    config.init(args)
    if os.environ.get('CNI_COMMAND') == 'VERSION':
        CONF.set_default('use_stderr', True)

    # Initialize o.vo registry.
    os_vif.initialize()

    runner = cni_api.CNIDaemonizedRunner()

    def _timeout(signum, frame):
        runner._write_dict(sys.stdout, {
            'msg': 'timeout',
            'code': consts.CNI_TIMEOUT_CODE,
        })
        LOG.debug('timed out')
        sys.exit(1)

    signal.signal(signal.SIGALRM, _timeout)
    signal.alarm(_CNI_TIMEOUT)
    status = runner.run(os.environ, cni_conf, sys.stdout)
    LOG.debug("Exiting with status %s", status)
    if status:
        sys.exit(status) 
Example #14
Source File: __init__.py    From searchlight with Apache License 2.0 5 votes vote down vote up
def _load_fixture_data(self, name):
        base_dir = "searchlight/tests/functional/data"
        # binary mode is needed due to bug/1515231
        with open(os.path.join(base_dir, name), 'r+b') as f:
            return jsonutils.load(f) 
Example #15
Source File: test_api.py    From searchlight with Apache License 2.0 5 votes vote down vote up
def _modify_policy_file(self, rules):
        with open(self.policy_file, 'r+b') as policy_file:
            existing_policy = jsonutils.load(policy_file)

        existing_policy.update(rules)

        with open(self.policy_file, 'w') as policy_file:
            jsonutils.dump(existing_policy, policy_file)

        time.sleep(2) 
Example #16
Source File: test_jsonutils.py    From oslo.serialization with Apache License 2.0 5 votes vote down vote up
def test_load(self):

        jsontext = u'{"a": "\u0442\u044d\u0441\u0442"}'
        expected = {u'a': u'\u0442\u044d\u0441\u0442'}

        for encoding in ('utf-8', 'cp1251'):
            fp = io.BytesIO(jsontext.encode(encoding))
            result = jsonutils.load(fp, encoding=encoding)
            self.assertEqual(expected, result)
            for key, val in result.items():
                self.assertIsInstance(key, str)
                self.assertIsInstance(val, str) 
Example #17
Source File: json_serializer.py    From oslo.serialization with Apache License 2.0 5 votes vote down vote up
def load(self, fp):
        return jsonutils.load(fp, encoding=self._encoding) 
Example #18
Source File: utils.py    From python-mistralclient with Apache License 2.0 5 votes vote down vote up
def load_json(input_string):
    try:
        # binary mode is needed due to bug/1515231
        with open(input_string, 'r+b') as fh:
            return jsonutils.load(fh)
    except IOError:
        return jsonutils.loads(input_string) 
Example #19
Source File: vhostuser.py    From kuryr-kubernetes with Apache License 2.0 5 votes vote down vote up
def _get_vhu_sock(config_file_path):
    with open(config_file_path, 'r') as f:
        conf = jsonutils.load(f)
    return conf['vhostname'] 
Example #20
Source File: main.py    From kuryr-kubernetes with Apache License 2.0 5 votes vote down vote up
def run():
    d = jsonutils.load(sys.stdin.buffer)
    cni_conf = utils.CNIConfig(d)
    args = (['--config-file', cni_conf.kuryr_conf] if 'kuryr_conf' in d
            else [])

    try:
        if cni_conf.debug:
            args.append('-d')
    except AttributeError:
        pass
    config.init(args)
    config.setup_logging()

    # Initialize o.vo registry.
    k_objects.register_locally_defined_vifs()
    os_vif.initialize()

    runner = cni_api.CNIDaemonizedRunner()

    def _timeout(signum, frame):
        runner._write_dict(sys.stdout, {
            'msg': 'timeout',
            'code': k_const.CNI_TIMEOUT_CODE,
        })
        LOG.debug('timed out')
        sys.exit(1)

    signal.signal(signal.SIGALRM, _timeout)
    signal.alarm(_CNI_TIMEOUT)
    status = runner.run(os.environ, cni_conf, sys.stdout)
    LOG.debug("Exiting with status %s", status)
    if status:
        sys.exit(status) 
Example #21
Source File: test_callback.py    From ara-archive with GNU General Public License v3.0 5 votes vote down vote up
def test_playbook_persistence(self):
        r_playbook = m.Playbook.query.first()
        tmpfile = os.path.join(self.app.config['ARA_TMP_DIR'], 'ara.json')

        with open(tmpfile, 'rb') as file:
            data = jsonutils.load(file)
        self.assertEqual(r_playbook.id, data['playbook']['id']) 
Example #22
Source File: filesystem.py    From glance_store with Apache License 2.0 4 votes vote down vote up
def _validate_metadata(self, metadata_file):
        """Validate metadata against json schema.

        If metadata is valid then cache metadata and use it when
        creating new image.

        :param metadata_file: JSON metadata file path
        :raises: BadStoreConfiguration exception if metadata is not valid.
        """
        try:
            with open(metadata_file, 'rb') as fptr:
                metadata = jsonutils.load(fptr)

            if isinstance(metadata, dict):
                # If metadata is of type dictionary
                # i.e. - it contains only one mountpoint
                # then convert it to list of dictionary.
                metadata = [metadata]

            # Validate metadata against json schema
            jsonschema.validate(metadata, MULTI_FILESYSTEM_METADATA_SCHEMA)
            glance_store.check_location_metadata(metadata)
            self.FILESYSTEM_STORE_METADATA = metadata
        except (jsonschema.exceptions.ValidationError,
                exceptions.BackendException, ValueError) as vee:
            err_msg = encodeutils.exception_to_unicode(vee)
            reason = _('The JSON in the metadata file %(file)s is '
                       'not valid and it can not be used: '
                       '%(vee)s.') % dict(file=metadata_file,
                                          vee=err_msg)
            LOG.error(reason)
            raise exceptions.BadStoreConfiguration(
                store_name="filesystem", reason=reason)
        except IOError as ioe:
            err_msg = encodeutils.exception_to_unicode(ioe)
            reason = _('The path for the metadata file %(file)s could '
                       'not be accessed: '
                       '%(ioe)s.') % dict(file=metadata_file,
                                          ioe=err_msg)
            LOG.error(reason)
            raise exceptions.BadStoreConfiguration(
                store_name="filesystem", reason=reason)