当前位置: 首页>>代码示例>>Python>>正文


Python munch.Munch类代码示例

本文整理汇总了Python中munch.Munch的典型用法代码示例。如果您正苦于以下问题:Python Munch类的具体用法?Python Munch怎么用?Python Munch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Munch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load_data_from

def load_data_from(file_name, mode=None, external_params_name=None):
    """We assume that 'external_params' is a a valid json if passed
    """

    external_params = BuiltIn().\
        get_variable_value('${{{name}}}'.format(name=external_params_name))

    if not os.path.exists(file_name):
        file_name = os.path.join(os.path.dirname(__file__), 'data', file_name)
    with open(file_name) as file_obj:
        if file_name.endswith('.json'):
            file_data = Munch.fromDict(load(file_obj))
        elif file_name.endswith('.yaml'):
            file_data = Munch.fromYAML(file_obj)
    if mode == 'brokers':
        default = file_data.pop('Default')
        brokers = {}
        for k, v in file_data.iteritems():
            brokers[k] = merge_dicts(default, v)
        file_data = brokers

    try:
        ext_params_munch \
            = Munch.fromDict(loads(external_params)) \
            if external_params else Munch()
    except ValueError:
        raise ValueError(
            'Value {param} of command line parameter {name} is invalid'.
            format(name=external_params_name, param=str(external_params))
        )

    return merge_dicts(file_data, ext_params_munch)
开发者ID:OSerhii,项目名称:robot_tests,代码行数:32,代码来源:service_keywords.py

示例2: NodeAPIResult

class NodeAPIResult(object):

    """Generic representation of a result from a call to the export API.
    """

    def __init__(self, data):
        if "nodelist" in data:
            self.nodelist = data["nodelist"]
            del data["nodelist"]
        if "result_shortlist" in data:
            self.shortlist = APIShortlist(data["result_shortlist"])
            del data["result_shortlist"]
        self.info = Munch(data)

    def __getitem__(self, key):
        return self.info[key]

    def __getattr__(self, name):
        return self.info.__getattr__(name)

    def iternode(self):
        return imap(APINode.from_dict, (l[0] for l in self.nodelist))

    def print_info(self):
        print(self.info.toYAML())
开发者ID:mediatum,项目名称:mediatum,代码行数:25,代码来源:objects.py

示例3: run

    def run(self):
        """ Handle action (other then builds) - like rename or delete of project """
        result = Munch()
        result.id = self.data["id"]

        action_type = self.data["action_type"]

        if action_type == ActionType.DELETE:
            if self.data["object_type"] == "copr":
                self.handle_delete_copr_project()
            elif self.data["object_type"] == "build":
                self.handle_delete_build()

            result.result = ActionResult.SUCCESS

        elif action_type == ActionType.LEGAL_FLAG:
            self.handle_legal_flag()

        elif action_type == ActionType.RENAME:
            self.handle_rename(result)

        elif action_type == ActionType.CREATEREPO:
            self.handle_createrepo(result)

        elif action_type == ActionType.UPDATE_COMPS:
            self.handle_comps_update(result)

        if "result" in result:
            if result.result == ActionResult.SUCCESS and \
                    not getattr(result, "job_ended_on", None):
                result.job_ended_on = time.time()

            self.frontend_client.update({"actions": [result]})
开发者ID:seocam,项目名称:copr,代码行数:33,代码来源:actions.py

示例4: execute_with_lock

    def execute_with_lock(self, executable: str, lock: ConnectedConsulLockInformation, *, capture_stdout: bool=False,
                          capture_stderr: bool=False) -> Tuple[int, Optional[bytes], Optional[bytes]]:
        """
        TODO
        :param executable:
        :param lock:
        :param capture_stdout:
        :param capture_stderr:
        :return:
        """
        assert lock is not None
        redirects = Munch(stdout=subprocess.PIPE if capture_stdout else sys.stdout,
                         stderr=subprocess.PIPE if capture_stderr else sys.stderr)

        # Patch for when sys.stdout and sys.stderr have been reassigned (e.g. in IDE test runners)
        non_realtime_redirects: Dict[str, StringIO] = {}
        for name, redirect in redirects.items():
            if isinstance(redirect, StringIO):
                logger.warning(f"Cannot capture {name} in real-time as `sys.{name}` does not have a fileno")
                non_realtime_redirects[name] = redirect
                redirects[name] = subprocess.PIPE

        outputs = Munch(stdout=None, stderr=None)
        with lock:
            process = subprocess.Popen(executable, shell=True, stdout=redirects.stdout, stderr=redirects.stderr)
            outputs.stdout, outputs.stderr = process.communicate()

        # Second part of redirect reassignment patch
        for name, original_redirect in non_realtime_redirects.items():
            captured = outputs[name]
            getattr(sys, name).write(captured.decode("utf-8"))

        return process.returncode, \
               outputs.stdout if capture_stdout else None, \
               outputs.stderr if capture_stderr else None
开发者ID:wtsi-hgi,项目名称:consul-lock,代码行数:35,代码来源:managers.py

示例5: _get_arguments

def _get_arguments(argv, environ):
    from .__version__ import __version__
    from docopt import docopt
    from munch import Munch

    project_default = "[default: {}]".format(environ["JISSUE_PROJECT"]) if "JISSUE_PROJECT" in environ else ""
    version_default = "[default: {}]".format(environ["JISSUE_VERSION"]) if "JISSUE_VERSION" in environ else ""
    component_default = "[default: {}]".format(environ["JISSUE_COMPONENT"]) if "JISSUE_COMPONENT" in environ else ""
    issue_default = "[default: {}]".format(environ["JISSUE_ISSUE"]) if "JISSUE_ISSUE" in environ else ""
    doc_with_defaults = __doc__.format(
        project_default=project_default,
        version_default=version_default,
        component_default=component_default,
        issue_default=issue_default,
        issue="[<issue>]" if issue_default else "<issue>",
        project="[<project>]" if project_default else "<project>",
    )
    arguments = Munch(docopt(doc_with_defaults, argv=argv, help=True, version=__version__))
    if environ.get("JISSUE_PROJECT") and not arguments.get("<project>"):
        arguments["<project>"] = environ["JISSUE_PROJECT"]
    if environ.get("JISSUE_VERSION") and not arguments.get("--fix-version"):
        arguments["--fix-version"] = environ["JISSUE_VERSION"]
    if environ.get("JISSUE_COMPONENT") and not arguments.get("<component>"):
        arguments["<component>"] = environ["JISSUE_COMPONENT"]
    if environ.get("JISSUE_ISSUE") and not arguments.get("<issue>"):
        arguments["<issue>"] = environ["JISSUE_ISSUE"]
    return arguments
开发者ID:Infinidat,项目名称:infi.jira_cli,代码行数:27,代码来源:jissue.py

示例6: test_static_price

def test_static_price(
        empty_proxy: PaywalledProxy,
        api_endpoint_address: str,
        client: Client,
        wait_for_blocks
):
    proxy = empty_proxy
    endpoint_url = "http://" + api_endpoint_address

    proxy.add_paywalled_resource(StaticPriceResource, '/resource', 3)

    # test GET
    response = requests.get(endpoint_url + '/resource')
    assert response.status_code == 402
    headers = HTTPHeaders.deserialize(response.headers)
    assert int(headers.price) == 3

    channel = client.get_suitable_channel(headers.receiver_address, int(headers.price) * 4)
    wait_for_blocks(6)
    channel.update_balance(int(headers.price))

    headers = Munch()
    headers.balance = str(channel.balance)
    headers.balance_signature = encode_hex(channel.balance_sig)
    headers.sender_address = channel.sender
    headers.open_block = str(channel.block)
    headers = HTTPHeaders.serialize(headers)

    response = requests.get(endpoint_url + '/resource', headers=headers)
    assert response.status_code == 200
    assert response.text.strip() == 'GET'

    assert_method(requests.post, endpoint_url + '/resource', headers, channel, 'POST')
    assert_method(requests.put, endpoint_url + '/resource', headers, channel, 'PUT')
    assert_method(requests.delete, endpoint_url + '/resource', headers, channel, 'DEL')
开发者ID:AlphaX-IBS,项目名称:microraiden,代码行数:35,代码来源:test_proxy.py

示例7: test_explicit_json

def test_explicit_json(
        empty_proxy: PaywalledProxy,
        api_endpoint_address: str,
        client: Client,
        wait_for_blocks
):
    proxy = empty_proxy
    endpoint_url = "http://" + api_endpoint_address

    proxy.add_paywalled_resource(JSONResource, '/resource', 3)

    # test GET
    response = requests.get(endpoint_url + '/resource')
    assert response.status_code == 402
    headers = HTTPHeaders.deserialize(response.headers)
    assert int(headers.price) == 3

    channel = client.get_suitable_channel(headers.receiver_address, int(headers.price) * 4)
    wait_for_blocks(6)
    channel.update_balance(int(headers.price))

    headers = Munch()
    headers.balance = str(channel.balance)
    headers.balance_signature = encode_hex(channel.balance_sig)
    headers.sender_address = channel.sender
    headers.open_block = str(channel.block)
    headers = HTTPHeaders.serialize(headers)

    response = requests.get(endpoint_url + '/resource', headers=headers)
    assert response.status_code == 200
    # If headers don't merge properly, this results in 'application/json,application/json'.
    assert response.headers['Content-Type'] == 'application/json'
    assert response.json() == {'GET': 1}
开发者ID:AlphaX-IBS,项目名称:microraiden,代码行数:33,代码来源:test_proxy.py

示例8: test_copy

def test_copy():
    m = Munch(urmom=Munch(sez=Munch(what='what')))
    c = m.copy()
    assert c is not m
    assert c.urmom is not m.urmom
    assert c.urmom.sez is not m.urmom.sez
    assert c.urmom.sez.what == 'what'
    assert c == m
开发者ID:Infinidat,项目名称:munch,代码行数:8,代码来源:test_munch.py

示例9: load_data_from_file

def load_data_from_file(file_name):
    if not os.path.exists(file_name):
        file_name = os.path.join(os.path.dirname(__file__), file_name)
    with open(file_name) as file_obj:
        if file_name.endswith(".json"):
            return Munch.fromDict(load(file_obj))
        elif file_name.endswith(".yaml"):
            return Munch.fromYAML(file_obj)
开发者ID:Valdisk92,项目名称:robot_tests,代码行数:8,代码来源:op_faker.py

示例10: test_setattr

def test_setattr():
    b = Munch(foo='bar', this_is='useful when subclassing')
    assert hasattr(b.values, '__call__')

    b.values = 'uh oh'
    assert b.values == 'uh oh'

    with pytest.raises(KeyError):
        b['values']
开发者ID:Infinidat,项目名称:munch,代码行数:9,代码来源:test_munch.py

示例11: identify

    def identify(self, environ):
        '''Extract information to identify a user

        Retrieve either a username and password or a session_id that can be
        passed on to FAS to authenticate the user.
        '''
        log.info('in identify()')

        # friendlyform compat
        if not 'repoze.who.logins' in environ:
            environ['repoze.who.logins'] = 0

        req = webob.Request(environ, charset='utf-8')
        cookie = req.cookies.get(self.session_cookie)

        # This is compatible with TG1 and it gives us a way to authenticate
        # a user without making two requests
        query = req.GET
        form = Munch(req.POST)
        form.update(query)
        if form.get('login', None) == 'Login' and \
                'user_name' in form and \
                'password' in form:
            identity = {
                'login': form['user_name'],
                'password': form['password']
            }
            keys = ('login', 'password', 'user_name')
            for k in keys:
                if k in req.GET:
                    del(req.GET[k])
                if k in req.POST:
                    del(req.POST[k])
            return identity

        if cookie is None:
            return None

        log.info('Request identify for cookie %(cookie)s' %
                 {'cookie': to_bytes(cookie)})
        try:
            user_data = self._retrieve_user_info(
                environ,
                auth_params={'session_id': cookie})
        except Exception as e:  # pylint:disable-msg=W0703
            # For any exceptions, returning None means we failed to identify
            log.warning(e)
            return None

        if not user_data:
            return None

        # Preauthenticated
        identity = {'repoze.who.userid': user_data[1]['username'],
                    'login': user_data[1]['username'],
                    'password': user_data[1]['password']}
        return identity
开发者ID:rodrigc,项目名称:python-fedora,代码行数:57,代码来源:faswhoplugin.py

示例12: __setattr__

    def __setattr__(self, k, v):
        """Recursive.

        >>> x=AutoBunch()
        >>> setattr(x, 'mega.name', 'xy')

        """
        k2, _, k3 = k.partition('.')
        if k3:
            self.__getattr__(k2).__setattr__(k3, v)
        else:
            Munch.__setattr__(self, k, v)
开发者ID:,项目名称:,代码行数:12,代码来源:

示例13: group_med_line

def group_med_line(x, y, **kwargs):
    opts = Munch(kwargs)

    y.index = x.values
    data = pd.DataFrame(y)
    meds = dict(data.reset_index().groupby('index').agg(np.median).iloc[:,0])

    if 'colors' not in opts.keys():
        opts.colors = {name: 'k' for name in meds.keys()}

    for name, val in meds.items():
        plt.axhline(y=val, linewidth=2, color=opts.colors[name], ls='solid', label=name, alpha=1)
开发者ID:xguse,项目名称:crunchers,代码行数:12,代码来源:plotting.py

示例14: __init__

    def __init__(self, conn, id = None, article_etree = None):
        """
        Article

        :param conn: Connection-Object
        """

        Bunch.__init__(self)

        self.conn = conn
        self.content_language = None

        self.id = id  # integer
        self.created = None  # datetime
        self.article_number = None
        self.number = None  # integer
        self.number_pre = None
        self.title = None
        self.description = None
        self.sales_price = None  # float
        self.sales_price2 = None  # float
        self.sales_price3 = None  # float
        self.sales_price4 = None  # float
        self.sales_price5 = None  # float
        self.currency_code = None
        self.unit_id = None  # integer
        self.tax_id = None  # integer
        self.purchase_price = None  # float
        self.purchase_price_net_gross = None
        self.supplier_id = None  # integer

        if article_etree is not None:
            self.load_from_etree(article_etree)
        elif id is not None:
            self.load()
开发者ID:gerold-penz,项目名称:python-billomat,代码行数:35,代码来源:articles.py

示例15: __init__

    def __init__(self, conn, id = None, reminder_item_etree = None):
        """
        Reminder-Item

        :param conn: Connection-Object
        """

        Bunch.__init__(self)

        self.conn = conn

        self.id = id  # integer
        self.created = None  # datetime
        self.article_id = None
        self.reminder_id = None  # integer
        self.position = None  # integer
        self.unit = None
        self.quantity = None  # float
        self.unit_price = None  # float
        self.title = None
        self.description = None
        self.total = None  # float

        if reminder_item_etree is not None:
            self.load_from_etree(reminder_item_etree)
        elif id is not None:
            self.load()
开发者ID:gerold-penz,项目名称:python-billomat,代码行数:27,代码来源:reminder_items.py


注:本文中的munch.Munch类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。