當前位置: 首頁>>代碼示例>>Python>>正文


Python munch.munchify方法代碼示例

本文整理匯總了Python中munch.munchify方法的典型用法代碼示例。如果您正苦於以下問題:Python munch.munchify方法的具體用法?Python munch.munchify怎麽用?Python munch.munchify使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在munch的用法示例。


在下文中一共展示了munch.munchify方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_config

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def get_config(default_file):
    p = argparse.ArgumentParser(description='Learned Step Size Quantization')
    p.add_argument('config_file', metavar='PATH', nargs='+',
                   help='path to a configuration file')
    arg = p.parse_args()

    with open(default_file) as yaml_file:
        cfg = yaml.safe_load(yaml_file)

    for f in arg.config_file:
        if not os.path.isfile(f):
            raise FileNotFoundError('Cannot find a configuration file at', f)
        with open(f) as yaml_file:
            c = yaml.safe_load(yaml_file)
            cfg = merge_nested_dict(cfg, c)

    return munch.munchify(cfg) 
開發者ID:zhutmost,項目名稱:lsq-net,代碼行數:19,代碼來源:config.py

示例2: test_fetch_got_data

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def test_fetch_got_data(self):
        queue_items = munchify({
            'items': [{
                'data': {
                    'id': 1
                },
                'meta': {
                    'type': 'user',
                    'sync': {
                        'event_type': 'created',
                        'ack_key': 'User-1234-1',
                        'revision': 1
                    }
                }
            }]
        })
        http_client = mock.create_autospec(basecrm.HttpClient)
        http_client.get.return_value = (200, {}, queue_items)

        sync = basecrm.SyncService(http_client)
        self.assertEquals(sync.fetch(self.device_uuid, self.session_id), queue_items['items'])
        http_client.get.assert_called_once_with("/sync/{session_id}/queues/main".format(session_id=self.session_id),
                                                params=None,
                                                headers={'X-Basecrm-Device-UUID': self.device_uuid},
                                                raw=True) 
開發者ID:zendesk,項目名稱:basecrm-python,代碼行數:27,代碼來源:test_sync_service.py

示例3: disableEditorTracking

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def disableEditorTracking(self):
        """Disables editor tracking."""
        capabilities = self.get(CAPABILITIES, '').split(',')
        editorInfo = self.get(EDITOR_TRACKING_INFO, {
            "enableEditorTracking": False,
            "enableOwnershipAccessControl": False,
            "allowOthersToUpdate": True,
            "allowOthersToDelete": True,
            "allowOthersToQuery": True,
            "allowAnonymousToUpdate": True,
            "allowAnonymousToDelete": True
          })
        editorInfo["enableEditorTracking"] = False

        # enable editor tracking at Feature Service level
        result = {}
        if CHANGE_TRACKING in capabilities:
            capabilities.remove(CHANGE_TRACKING)
            capabilities = ','.join(capabilities)
            result['disabled_at_feature_service'] = self.updateDefinition({CAPABILITIES: capabilities, HAS_STATIC_DATA: self.get(HAS_STATIC_DATA), EDITOR_TRACKING_INFO: editorInfo})
        else:
            result['disabled_at_feature_service'] = {'status': 'already disabled'}

        return munch.munchify(result) 
開發者ID:Bolton-and-Menk-GIS,項目名稱:restapi,代碼行數:26,代碼來源:__init__.py

示例4: createNewDateFieldDefinition

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def createNewDateFieldDefinition(name, alias='', autoUpdate=False):
        """Creates a json definition for a new date field.

        Args
            name: Name of new date field.
            alias: Optional field name for alias.
            autoUpdate: Optional boolean to automatically populate the field 
                with the current date/time when a new record is added or updated 
                (like editor tracking). The default is False.
        """

        return munch.munchify({
            NAME: name,
            TYPE: DATE_FIELD,
            ALIAS: alias or name,
            SQL_TYPE: SQL_TYPE_OTHER,
            NULLABLE: FALSE,
            EDITABLE: TRUE,
            DOMAIN: NULL,
            DEFAULT_VALUE: SQL_AUTO_DATE_EXP if autoUpdate else NULL
        }) 
開發者ID:Bolton-and-Menk-GIS,項目名稱:restapi,代碼行數:23,代碼來源:__init__.py

示例5: getFeatureExtent

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def getFeatureExtent(in_features):
    """Gets the extent for a FeatureSet() or GeometryCollection(), must be convertible
    to a GeometryCollection().

    Arg:
        in_features: Input features (Feature|FeatureSet|GeometryCollection|json).
    
    Returns:
        An envelope json structure (extent).
    """

    if not isinstance(in_features, GeometryCollection):
        in_features = GeometryCollection(in_features)

    extents = [g.envelopeAsJSON() for g in iter(in_features)]
    full_extent = {SPATIAL_REFERENCE: extents[0].get(SPATIAL_REFERENCE)}
    for attr, op in {XMIN: min, YMIN: min, XMAX: max, YMAX: max}.iteritems():
        full_extent[attr] = op([e.get(attr) for e in extents])
    return munch.munchify(full_extent) 
開發者ID:Bolton-and-Menk-GIS,項目名稱:restapi,代碼行數:21,代碼來源:common_types.py

示例6: unqualify_fields

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def unqualify_fields(fs):
    """Removes fully qualified field names from a feature set.

    Arg:
        fs: restapi.FeatureSet() object or JSON.
    """

    if not isinstance(fs, FeatureSet):
        fs = FeatureSet(fs)

    clean_fields = {}
    for f in fs.fields:
        if f:
            clean = f.name.split('.')[-1]
            clean_fields[f.name] = clean
            f.name = clean

    for i,feature in enumerate(fs.features):
        feature_copy = {}
        for f, val in six.iteritems(feature.attributes):
            feature_copy[clean_fields.get(f, f)] = val
        fs.features[i].attributes = munch.munchify(feature_copy) 
開發者ID:Bolton-and-Menk-GIS,項目名稱:restapi,代碼行數:24,代碼來源:common_types.py

示例7: _spatialReference

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def _spatialReference(self):
        """Gets the spatial reference dict."""
        resp_d = {}
        if SPATIAL_REFERENCE in self.json:
            resp_d = self.json[SPATIAL_REFERENCE]
        elif self.json.get(EXTENT) and SPATIAL_REFERENCE in self.json[EXTENT]:
            resp_d = self.json[EXTENT][SPATIAL_REFERENCE]
        elif GEOMETRIES in self.json:
            try:
                first = self.json.get(GEOMETRIES, [])[0]
                resp_d = first.get(SPATIAL_REFERENCE) or {}
            except IndexError:
                pass
        elif CRS in self.json:
            resp_d = self.json.get(CRS, {})
        return munch.munchify(resp_d) 
開發者ID:Bolton-and-Menk-GIS,項目名稱:restapi,代碼行數:18,代碼來源:rest_utils.py

示例8: __init__

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def __init__(self, in_json):
        """Inits class with JSON as geo feature set.

        Arg:
            in_json: Input json response from request.
        """

        if isinstance(in_json, six.string_types):
            if not in_json.startswith('{') and os.path.isfile(in_json):
                with open(in_json, 'r') as f:
                    in_json = json.load(f)
            else:
                in_json = json.loads(in_json)
        if isinstance(in_json, self.__class__):
            self.json = in_json.json
        elif isinstance(in_json, dict):
            self.json = munch.munchify(in_json) 
開發者ID:Bolton-and-Menk-GIS,項目名稱:restapi,代碼行數:19,代碼來源:rest_utils.py

示例9: _load_global_setting

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def _load_global_setting(self, candidate, variables):
        """
        Load and render global setting with variables.
        :param candidate: Global setting as a `dict`
        :param variables: variables from context to render setting
        :return: A `Munch` object
        """
        candidate = candidate or {}
        proxy_setting = self._load_proxy(candidate.get('proxy'), variables)
        log_setting = self._load_logging(candidate.get('logging'), variables)

        return munchify({'proxy': proxy_setting, 'logging': log_setting}) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:14,代碼來源:loader.py

示例10: _load_request

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def _load_request(self, request):
        options = self._load_options(request['request'])

        pre_process = self._load_processor(request.get('pre_process', {}))
        post_process = self._load_processor(request['post_process'])
        checkpoint = self._load_checkpoint(request.get('checkpoint'))
        iteration_mode = self._load_iteration_mode(request['iteration_mode'])

        return munchify({
            'request': options,
            'pre_process': pre_process,
            'post_process': post_process,
            'checkpoint': checkpoint,
            'iteration_mode': iteration_mode,
        }) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:17,代碼來源:loader.py

示例11: load

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def load(self, definition, schema_file, context):
        """Load cloud connect configuration from a `dict` and validate
        it with schema and global settings will be rendered.
        :param schema_file: Schema file location used to validate config.
        :param definition: A dictionary contains raw configs.
        :param context: variables to render template in global setting.
        :return: A `Munch` object.
        """
        try:
            validate(definition, self._get_schema_from_file(schema_file))
        except ValidationError:
            raise ConfigException(
                'Failed to validate interface with schema: {}'.format(
                    traceback.format_exc()))

        try:
            global_settings = self._load_global_setting(
                definition.get('global_settings'), context
            )

            requests = [self._load_request(item) for item in definition['requests']]

            return munchify({
                'meta': munchify(definition['meta']),
                'tokens': definition['tokens'],
                'global_settings': global_settings,
                'requests': requests,
            })
        except Exception as ex:
            error = 'Unable to load configuration: %s' % str(ex)
            _logger.exception(error)
            raise ConfigException(error) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:34,代碼來源:loader.py

示例12: read_config

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def read_config():
    """Attempts to read the application configuration file and will raise a `FileNotFoundError` if the
    configuration file is not found. Returns the folder where the configuration file was loaded from, and
    a `Munch` (dict-like object) containing the configuration

    Configuration file paths searched, in order:
        * ~/.cinq/config.json'
        * ./config.json
        * /usr/local/etc/cloud-inquisitor/config.json

    Returns:
        `str`, `dict`
    """
    def __recursive_update(old, new):
        out = deepcopy(old)
        for k, v in new.items():
            if issubclass(type(v), dict):
                if k in old:
                    out[k] = __recursive_update(old[k], v)
                else:
                    out[k] = v
            else:
                out[k] = v

        return out

    for fpath in CONFIG_FILE_PATHS:
        if os.path.exists(fpath):
            data = munch.munchify(json.load(open(fpath, 'r')))

            # Our code expects a munch, so ensure that any regular dicts are converted
            return os.path.dirname(fpath), munch.munchify(__recursive_update(DEFAULT_CONFIG, data))

    raise FileNotFoundError('Configuration file not found') 
開發者ID:RiotGames,項目名稱:cloud-inquisitor,代碼行數:36,代碼來源:utils.py

示例13: new_build

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def new_build(profile='cbs', scratch=True):
    # Very ugly: some utilities are only available in koji CLI
    # and not in the koji module
    if not KOJI_AVAILABLE:
        raise ModuleNotAvailable(module='koji')
    if not RPM_AVAILABLE:
        raise RpmModuleNotAvailable()
    import imp
    kojibin = find_executable('koji')
    kojicli = imp.load_source('kojicli', kojibin)
    # Koji 1.13 moves client internal API into another path
    try:
        from koji_cli.lib import _unique_path, _progress_callback, watch_tasks
    except ImportError:
        from kojicli import _unique_path, _progress_callback, watch_tasks

    kojiclient = setup_kojiclient(profile)
    # Note: required to make watch_tasks work
    kojicli.options = opts = munchify(kojiclient.opts)
    build_target = guess_build()
    if not build_target:
        log.warn("failed to identify build tag from branch")
        return

    retrieve_sources()
    srpm = create_srpm()
    if not srpm:
        log.warn('No srpm available')
        return
    serverdir = _unique_path('cli-build')
    kojiclient.uploadWrapper(srpm, serverdir, callback=_progress_callback)
    source = "%s/%s" % (serverdir, os.path.basename(srpm))
    task_id = kojiclient.build(source, build_target, {'scratch': scratch})
    print("Created task:", task_id)

    print("Task info: {}/taskinfo?taskID={}".format(opts['weburl'], task_id))
    kojiclient.logout()
    watch_tasks(kojiclient, [task_id]) 
開發者ID:softwarefactory-project,項目名稱:rdopkg,代碼行數:40,代碼來源:cbsbuild.py

示例14: unwrap_envelope

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def unwrap_envelope(body):
        return [munchify(item['data']) for item in body['items']] if 'items' in body else munchify(body['data']) 
開發者ID:zendesk,項目名稱:basecrm-python,代碼行數:4,代碼來源:http_client.py

示例15: __init__

# 需要導入模塊: import munch [as 別名]
# 或者: from munch import munchify [as 別名]
def __init__(self, http_status, errors_payload):
        """
        :param int http_status: Http status code.
        :param dict errors_payload: Json decoded payload from the errors response.
        """
        self.http_status = http_status
        self.errors = [munchify(error_envelope['error'])
                       for error_envelope in errors_payload['errors']]
        self.logref = errors_payload['meta']['logref']

        message = "\n".join([str(error) for error in self.errors])
        super(BaseError, self).__init__(message) 
開發者ID:zendesk,項目名稱:basecrm-python,代碼行數:14,代碼來源:errors.py


注:本文中的munch.munchify方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。