Python werkzeug.datastructures.ImmutableDict() Examples

The following are 10 code examples of werkzeug.datastructures.ImmutableDict(). 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 werkzeug.datastructures , or try the search function .
Example #1
Source File: util.py    From indico-plugins with MIT License 6 votes vote down vote up
def obj_ref(obj):
    """Returns a tuple identifying a category/event/contrib/subcontrib"""
    from indico_livesync.models.queue import EntryType
    if isinstance(obj, Category):
        ref = {'type': EntryType.category, 'category_id': obj.id}
    elif isinstance(obj, Event):
        ref = {'type': EntryType.event, 'event_id': obj.id}
    elif isinstance(obj, Session):
        ref = {'type': EntryType.session, 'session_id': obj.id}
    elif isinstance(obj, Contribution):
        ref = {'type': EntryType.contribution, 'contrib_id': obj.id}
    elif isinstance(obj, SubContribution):
        ref = {'type': EntryType.subcontribution, 'subcontrib_id': obj.id}
    else:
        raise ValueError('Unexpected object: {}'.format(obj.__class__.__name__))
    return ImmutableDict(ref) 
Example #2
Source File: queue.py    From indico-plugins with MIT License 5 votes vote down vote up
def object_ref(self):
        """Return the reference of the changed object."""
        return ImmutableDict(type=self.type, category_id=self.category_id, event_id=self.event_id,
                             session_id=self.session_id, contrib_id=self.contrib_id, subcontrib_id=self.subcontrib_id) 
Example #3
Source File: allows.py    From flask-allows with MIT License 5 votes vote down vote up
def run(
        self,
        requirements,
        identity=None,
        throws=None,
        on_fail=None,
        f_args=(),
        f_kwargs=ImmutableDict(),  # noqa: B008
        use_on_fail_return=True,
    ):
        """
        Used to preform a full run of the requirements and the options given,
        this method will invoke on_fail and/or throw the appropriate exception
        type. Can be passed arguments to call on_fail with via f_args (which are
        passed positionally) and f_kwargs (which are passed as keyword).

        :param requirements: The requirements to check
        :param identity: Optional. A specific identity to use for the check
        :param throws: Optional. A specific exception to throw for this check
        :param on_fail: Optional. A callback to invoke after failure,
            alternatively a value to return when failure happens
        :param f_args: Positional arguments to pass to the on_fail callback
        :param f_kwargs: Keyword arguments to pass to the on_fail callback
        :param use_on_fail_return: Boolean (default True) flag to determine
            if the return value should be used. If true, the return value
            will be considered, else failure will always progress to
            exception raising.
        """

        throws = throws or self.throws
        on_fail = _make_callable(on_fail) if on_fail is not None else self.on_fail

        if not self.fulfill(requirements, identity):
            result = on_fail(*f_args, **f_kwargs)
            if use_on_fail_return and result is not None:
                return result
            raise throws 
Example #4
Source File: dataframe.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def __new__(cls, unit, qty, price, groupby, metadata):
        return _DataPointBase.__new__(
            cls,
            unit or "undefined",
            # NOTE(peschk_l): avoids floating-point issues.
            decimal.Decimal(str(qty) if isinstance(qty, float) else qty),
            decimal.Decimal(str(price) if isinstance(price, float) else price),
            datastructures.ImmutableDict(groupby),
            datastructures.ImmutableDict(metadata),
        ) 
Example #5
Source File: dataframe.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def desc(self):
        output = dict(self.metadata)
        output.update(self.groupby)
        return datastructures.ImmutableDict(output) 
Example #6
Source File: dataframe.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def as_dict(self, legacy=False, mutable=False):
        output = {
            "period": {"begin": self.start, "end": self.end},
            "usage": {
                key: [v.as_dict(legacy=legacy, mutable=mutable) for v in val]
                for key, val in self._usage.items()
            },
        }
        return output if mutable else datastructures.ImmutableDict(output) 
Example #7
Source File: test_dataframe.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def test_as_dict_immutable(self):
        point_dict = dataframe.DataPoint(**self.default_params).as_dict()
        self.assertIsInstance(point_dict, datastructures.ImmutableDict)
        self.assertEqual(dict(point_dict), {
            "vol": {"unit": "undefined", "qty": decimal.Decimal(0)},
            "rating": {"price": decimal.Decimal(0)},
            "groupby": {},
            "metadata": {},
        }) 
Example #8
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_default_converters(self):
        class MyMap(r.Map):
            default_converters = r.Map.default_converters.copy()
            default_converters['foo'] = r.UnicodeConverter
        assert isinstance(r.Map.default_converters, ImmutableDict)
        m = MyMap([
            r.Rule('/a/<foo:a>', endpoint='a'),
            r.Rule('/b/<foo:b>', endpoint='b'),
            r.Rule('/c/<c>', endpoint='c')
        ], converters={'bar': r.UnicodeConverter})
        a = m.bind('example.org', '/')
        assert a.match('/a/1') == ('a', {'a': '1'})
        assert a.match('/b/2') == ('b', {'b': '2'})
        assert a.match('/c/3') == ('c', {'c': '3'})
        assert 'foo' not in r.Map.default_converters 
Example #9
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_default_converters(self):
        class MyMap(r.Map):
            default_converters = r.Map.default_converters.copy()
            default_converters['foo'] = r.UnicodeConverter
        assert isinstance(r.Map.default_converters, ImmutableDict)
        m = MyMap([
            r.Rule('/a/<foo:a>', endpoint='a'),
            r.Rule('/b/<foo:b>', endpoint='b'),
            r.Rule('/c/<c>', endpoint='c')
        ], converters={'bar': r.UnicodeConverter})
        a = m.bind('example.org', '/')
        assert a.match('/a/1') == ('a', {'a': '1'})
        assert a.match('/b/2') == ('b', {'b': '2'})
        assert a.match('/c/3') == ('c', {'c': '3'})
        assert 'foo' not in r.Map.default_converters 
Example #10
Source File: dataframe.py    From cloudkitty with Apache License 2.0 4 votes vote down vote up
def as_dict(self, legacy=False, mutable=False):
        """Returns a dict representation of the object.

        The returned dict is immutable by default and has the
        following format::
           {
               "vol": {
                   "unit": "GiB",
                   "qty": 1.2,
               },
               "rating": {
                   "price": 0.04,
               },
               "groupby": {
                   "group_one": "one",
                   "group_two": "two",
               },
               "metadata": {
                   "attr_one": "one",
                   "attr_two": "two",
                },
           }

        The dict can also be returned in the legacy (v1 storage) format. In
        that case, `groupby` and `metadata` will be removed and merged together
        into the `desc` key.

        :param legacy: Defaults to False. If True, returned dict is in legacy
                       format.
        :type legacy: bool
        :param mutable: Defaults to False. If True, returns a normal dict
                        instead of an ImmutableDict.
        :type mutable: bool
        """
        output = {
            "vol": {
                "unit": self.unit,
                "qty": self.qty,
            },
            "rating": {
                "price": self.price,
            },
            "groupby": dict(self.groupby) if mutable else self.groupby,
            "metadata": dict(self.metadata) if mutable else self.metadata,
        }
        if legacy:
            desc = output.pop("metadata")
            desc.update(output.pop("groupby"))
            output['desc'] = desc

        return output if mutable else datastructures.ImmutableDict(output)