Python types.MappingProxyType() Examples

The following are code examples for showing how to use types.MappingProxyType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: fs_image   Author: facebookincubator   File: subvolume_set.py    MIT License 6 votes vote down vote up
def freeze(self, *, _memo) -> 'SubvolumeSet':
        '''
        Return a recursively immutable copy of `self`, replacing all
        `IncompleteInode`s by `Inode`s, and checking that all inode metadata
        are populated.  Correctly resolving cloned extents has to happen at
        the level of the `SubvolumeSet`.
        '''
        id_to_chunks = dict(extents_to_chunks_with_clones(
            list(itertools.chain.from_iterable(
                subvol._inode_ids_and_extents()
                    for subvol in self.uuid_to_subvolume.values()
            ))
        ))
        return type(self)(
            uuid_to_subvolume=MappingProxyType({
                uuid: freeze(subvol, _memo=_memo, id_to_chunks=id_to_chunks)
                    for uuid, subvol in self.uuid_to_subvolume.items()
            }),
            name_uuid_prefix_counts=freeze(
                self.name_uuid_prefix_counts, _memo=_memo,
            ),
        ) 
Example 2
Project: adh6   Author: bonnetn   File: context.py    GNU General Public License v3.0 6 votes vote down vote up
def build_context(ctx: MappingProxyType = None, session=None, admin=None, testing=None, request_id=None):
    """

    :rtype:
    """
    new_fields = {
        CTX_SQL_SESSION: session,
        CTX_ADMIN: admin,
        CTX_TESTING: testing,
        CTX_REQUEST_ID: request_id,
    }
    if ctx is None:
        return MappingProxyType(new_fields)

    old_fields = {k: v for k, v in ctx.items() if v is not None}  # Remove None fields.

    merged = {**new_fields, **old_fields}  # Merge old and new context, with priority for the new one.

    return MappingProxyType(merged) 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: test_builtin.py    GNU General Public License v3.0 6 votes vote down vote up
def test_bad_args(self):
        with self.assertRaises(TypeError):
            type()
        with self.assertRaises(TypeError):
            type('A', ())
        with self.assertRaises(TypeError):
            type('A', (), {}, ())
        with self.assertRaises(TypeError):
            type('A', (), dict={})
        with self.assertRaises(TypeError):
            type('A', [], {})
        with self.assertRaises(TypeError):
            type('A', (), types.MappingProxyType({}))
        with self.assertRaises(TypeError):
            type('A', (None,), {})
        with self.assertRaises(TypeError):
            type('A', (bool,), {})
        with self.assertRaises(TypeError):
            type('A', (int, str), {}) 
Example 4
Project: aiohttp_admin   Author: aio-libs   File: utils.py    Apache License 2.0 6 votes vote down vote up
def validate_query(query, possible_columns):
    q = validate_query_structure(query)
    sort_field = q.get('_sortField')

    filters = q.get('_filters', [])
    columns = [field_name for field_name in filters]

    if sort_field is not None:
        columns.append(sort_field)

    not_valid = set(columns).difference(
        possible_columns + [MULTI_FIELD_TEXT_QUERY])
    if not_valid:
        column_list = ', '.join(not_valid)
        msg = 'Columns: {} do not present in resource'.format(column_list)
        raise JsonValidaitonError(msg)
    return MappingProxyType(q) 
Example 5
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_historical_float(self):
        """Tests openexchangerate.OpenExchangeRateClient.historical()."""
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)))
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_HISTORICAL %
                               self._date,
                               body=self._FIXTURE_LATEST)
        historical = client.historical(self._date)

        self.assertIsInstance(historical, tuple)
        self.assertIsInstance(historical.dict, dict)
        self.assertIsInstance(historical.frozendict, frozendict)

        self.assertIn('AED', historical.dict)
        self.assertEqual(historical.dict['AED'], 3.666311)
        self.assertIn('AFN', historical.dict)
        self.assertEqual(historical.dict['AFN'], 51.2281)
        self.assertIn('ALL', historical.dict)
        self.assertEqual(historical.dict['ALL'], 104.748751)
        self.assertIn('USD', historical.dict)
        self.assertEqual(historical.dict['USD'], 1.0) 
Example 6
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_historical_decimal(self):
        """Tests openexchangerate.OpenExchangeRateClient.historical()."""
        client = openexchangerate.OpenExchangeRates('DUMMY_API_KEY',
                                                           use_float=False)
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_HISTORICAL %
                               self._date,
                               body=self._FIXTURE_LATEST)
        historical = client.historical(self._date)

        self.assertIsInstance(historical, tuple)
        self.assertIsInstance(historical.dict, dict)
        self.assertIsInstance(historical.frozendict, frozendict)

        self.assertIn('AED', historical.dict)
        self.assertEqual(historical.dict['AED'], decimal.Decimal('3.666311'))
        self.assertIn('AFN', historical.dict)
        self.assertEqual(historical.dict['AFN'], decimal.Decimal('51.2281'))
        self.assertIn('ALL', historical.dict)
        self.assertEqual(historical.dict['ALL'], decimal.Decimal('104.748751'))
        self.assertIn('USD', historical.dict)
        self.assertEqual(historical.dict['USD'], decimal.Decimal('1')) 
Example 7
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_currencies_float(self):
        """Tests openexchangerate.OpenExchangeRateClient.currencies()."""
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)))
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_CURRENCIES,
                               body=self._FIXTURE_CURRENCIES)
        currencies = client.currencies()

        self.assertIsInstance(currencies, tuple)
        self.assertIsInstance(currencies.dict, dict)
        self.assertIsInstance(currencies.frozendict, frozendict)

        self.assertIn('AED', currencies.dict)
        self.assertIn('AFN', currencies.dict)
        self.assertIn('ALL', currencies.dict)
        self.assertIn('USD', currencies.dict) 
Example 8
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_latest_float(self):
        """Tests openexchangerate.OpenExchangeRateClient.latest()."""
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)))
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_LATEST,
                               body=self._FIXTURE_LATEST)
        latest = client.latest()

        self.assertIsInstance(latest, tuple)
        self.assertIsInstance(latest.dict, dict)
        self.assertIsInstance(latest.frozendict, frozendict)

        self.assertIn('AED', latest.dict)
        self.assertEqual(latest.dict['AED'], 3.666311)
        self.assertIn('AFN', latest.dict)
        self.assertEqual(latest.dict['AFN'], 51.2281)
        self.assertIn('ALL', latest.dict)
        self.assertEqual(latest.dict['ALL'], 104.748751)
        self.assertIn('USD', latest.dict)
        self.assertEqual(latest.dict['USD'], 1.0) 
Example 9
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_latest_decimal(self):
        """Tests openexchangerate.OpenExchangeRateClient.latest()."""
        client = openexchangerate.OpenExchangeRates('DUMMY_API_KEY',
                                                           use_float=False)
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_LATEST,
                               body=self._FIXTURE_LATEST)
        latest = client.latest()

        self.assertIsInstance(latest, tuple)
        self.assertIsInstance(latest.dict, dict)
        self.assertIsInstance(latest.frozendict, frozendict)

        self.assertIn('AED', latest.dict)
        self.assertEqual(latest.dict['AED'], decimal.Decimal('3.666311'))
        self.assertIn('AFN', latest.dict)
        self.assertEqual(latest.dict['AFN'], decimal.Decimal('51.2281'))
        self.assertIn('ALL', latest.dict)
        self.assertEqual(latest.dict['ALL'], decimal.Decimal('104.748751'))
        self.assertIn('USD', latest.dict)
        self.assertEqual(latest.dict['USD'], decimal.Decimal('1')) 
Example 10
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_historical_with_local_base_conversion_float(self):
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)), local_base='AED')
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_HISTORICAL %
                               self._date,
                               body=self._FIXTURE_HISTORICAL)
        historical_conversion = client.historical(self._date)

        self.assertIsInstance(historical_conversion, tuple)
        self.assertIsInstance(historical_conversion.dict, dict)
        self.assertIsInstance(historical_conversion.frozendict, frozendict)

        self.assertEqual(historical_conversion.dict['AED'], 1.0)
        self.assertEqual(historical_conversion.dict['AFN'], 13.97265535)
        self.assertEqual(historical_conversion.dict['ALL'], 28.57061253)
        self.assertEqual(historical_conversion.dict['USD'], 0.27275373) 
Example 11
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_historical_with_local_base_conversion_decimal(self):
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', use_float=False, local_base='AED')
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_HISTORICAL %
                               "2012-12-12",
                               body=self._FIXTURE_HISTORICAL)
        histo_cn = client.historical("2012-12-12")

        self.assertIsInstance(histo_cn, tuple)
        self.assertIsInstance(histo_cn.dict, dict)
        self.assertIsInstance(histo_cn.frozendict, frozendict)

        self.assertEqual(histo_cn.dict['AED'], decimal.Decimal('1.0'))
        self.assertEqual(histo_cn.dict['AFN'], decimal.Decimal('13.97265535'))
        self.assertEqual(histo_cn.dict['ALL'], decimal.Decimal('28.57061253'))
        self.assertEqual(histo_cn.dict['USD'], decimal.Decimal('0.27275373')) 
Example 12
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 6 votes vote down vote up
def test_contextmanager(self):
        """Tests openexchangerate.OpenExchangeRateClient.latest()."""
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', round_float=bool(randint(0, 1)))
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_LATEST,
                               body=self._FIXTURE_LATEST)
        with client as exchange_prices:
            self.assertIsInstance(exchange_prices, tuple)
            self.assertIsInstance(exchange_prices.dict, dict)
            self.assertIsInstance(exchange_prices.frozendict, frozendict)

            self.assertIn('AED', exchange_prices.dict)
            self.assertEqual(exchange_prices.dict['AED'], 3.666311)
            self.assertIn('AFN', exchange_prices.dict)
            self.assertEqual(exchange_prices.dict['AFN'], 51.2281)
            self.assertIn('ALL', exchange_prices.dict)
            self.assertEqual(exchange_prices.dict['ALL'], 104.748751)
            self.assertIn('USD', exchange_prices.dict)
            self.assertEqual(exchange_prices.dict['USD'], 1.0) 
Example 13
Project: openexchangerate   Author: juancarlospaco   File: openexchangerate.py    GNU General Public License v3.0 6 votes vote down vote up
def html(self, prices_data_dict: dict):
        names_get = self.currencies().frozendict.get
        prices = tuple(enumerate(prices_data_dict.items()))
        row = "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>"
        h = "<thead><th>#</th><th>Code</th><th>Price</th><th>Name</th></thead>"

        rows = [row.format(index, mony[0], mony[1], names_get(mony[0], "???"))
                for index, mony in prices
                if mony[0] not in ("EUR", "USD")]  # Skip Dollar and Euro.

        prio = [row.format(index, mony[0], mony[1], names_get(mony[0], "???"))
                for index, mony in prices
                if mony[0] in ("EUR", "USD")]  # Move Dollar and Euro at Top.

        return (f"<table>{ h if self.html_table_header else ''}"
                f"<tbody>{' '.join(prio + rows)}</tbody></table>") 
Example 14
Project: pycoalaip   Author: COALAIP   File: data_formats.py    Apache License 2.0 6 votes vote down vote up
def _make_context_immutable(context):
    """Best effort attempt at turning a properly formatted context
    (either a string, dict, or array of strings and dicts) into an
    immutable data structure.

    If we get an array, make it immutable by creating a tuple; if we get
    a dict, copy it into a MappingProxyType. Otherwise, return as-is.
    """
    def make_immutable(val):
        if isinstance(val, Mapping):
            return MappingProxyType(val)
        else:
            return val

    if not isinstance(context, (str, Mapping)):
        try:
            return tuple([make_immutable(val) for val in context])
        except TypeError:
            pass
    return make_immutable(context) 
Example 15
Project: edgedb   Author: edgedb   File: lexer.py    Apache License 2.0 6 votes vote down vote up
def __init_subclass__(cls):
        if not hasattr(cls, 'states'):
            return

        re_states = {}
        for state, rules in cls.states.items():
            res = []
            for rule in rules:
                if cls.asbytes:
                    res.append(b'(?P<%b>%b)' % (rule.id.encode(), rule.regexp))
                else:
                    res.append('(?P<{}>{})'.format(rule.id, rule.regexp))

            if cls.asbytes:
                res.append(b'(?P<err>.)')
            else:
                res.append('(?P<err>.)')

            if cls.asbytes:
                full_re = b' | '.join(res)
            else:
                full_re = ' | '.join(res)
            re_states[state] = re.compile(full_re, cls.RE_FLAGS)

        cls.re_states = types.MappingProxyType(re_states) 
Example 16
Project: fs_image   Author: facebookincubator   File: subvolume.py    MIT License 5 votes vote down vote up
def freeze(
        self,
        *,
        _memo,
        id_to_chunks: Optional[Mapping[InodeID, Sequence['Chunk']]]=None,
    ):
        '''
        Returns a recursively immutable copy of `self`, replacing
        `IncompleteInode`s by `Inode`s, using the provided `id_to_chunks` to
        populate them with `Chunk`s instead of `Extent`s.

        If `id_to_chunks` is omitted, we'll detect clones only within `self`.

        IMPORTANT: Our lookups assume that the `id_to_chunks` has the
        pre-`freeze` variants of the `InodeID`s.
        '''
        if id_to_chunks is None:
            id_to_chunks = dict(extents_to_chunks_with_clones(
                list(self._inode_ids_and_extents()),
            ))
        return type(self)(
            id_map=freeze(self.id_map, _memo=_memo),
            id_to_inode=MappingProxyType({
                freeze(id, _memo=_memo):
                        freeze(ino, _memo=_memo, chunks=id_to_chunks.get(id))
                    for id, ino in self.id_to_inode.items()
            }),
        ) 
Example 17
Project: fs_image   Author: facebookincubator   File: freeze.py    MIT License 5 votes vote down vote up
def freeze(obj, *, _memo=None, **kwargs):
    # Don't bother memoizing primitive types
    if isinstance(obj, (bytes, Enum, float, int, str, type(None))):
        return obj

    if _memo is None:
        _memo = {}

    if id(obj) in _memo:  # Already frozen?
        return _memo[id(obj)]

    if hasattr(obj, 'freeze'):
        frozen = obj.freeze(_memo=_memo, **kwargs)
    else:
        # At the moment, I don't have a need for passing extra data into
        # items that live inside containers.  If we're relaxing this, just
        # be sure to add `**kwargs` to each `freeze()` call below.
        assert kwargs == {}, kwargs
        # This is a lame-o way of identifying `NamedTuple`s. Using
        # `deepfrozen` would avoid this kludge.
        if (
            isinstance(obj, tuple) and hasattr(obj, '_replace') and
            hasattr(obj, '_fields') and hasattr(obj, '_make')
        ):
            frozen = obj._make(freeze(i, _memo=_memo) for i in obj)
        elif isinstance(obj, (list, tuple)):
            frozen = tuple(freeze(i, _memo=_memo) for i in obj)
        elif isinstance(obj, dict):
            frozen = MappingProxyType({
                freeze(k, _memo=_memo): freeze(v, _memo=_memo)
                    for k, v in obj.items()
            })
        elif isinstance(obj, (set, frozenset)):
            frozen = frozenset(freeze(i, _memo=_memo) for i in obj)
        else:
            raise NotImplementedError(type(obj))

    _memo[id(obj)] = frozen
    return frozen 
Example 18
Project: fs_image   Author: facebookincubator   File: test_freeze.py    MIT License 5 votes vote down vote up
def test_memo(self):
        l = []
        memo = {}
        d = {'inner': {1: l, 2: l}}
        fd = freeze(d, _memo=memo)
        self.assertEqual({'inner': {1: (), 2: ()}}, fd)
        self.assertIsInstance(fd, MappingProxyType)
        self.assertIsInstance(fd['inner'], MappingProxyType)
        self.assertIs(fd['inner'][1], fd['inner'][2])
        self.assertEqual({id(d), id(d['inner']), id(l)}, set(memo.keys())) 
Example 19
Project: fs_image   Author: facebookincubator   File: test_freeze.py    MIT License 5 votes vote down vote up
def test_containers(self):
        f = freeze([([]), {5}, frozenset([7]), {'a': 'b'}])
        self.assertEqual(((()), {5}, {7}, {'a': 'b'}), f)
        self.assertEqual(
            [tuple, frozenset, frozenset, MappingProxyType],
            [type(i) for i in f],
        ) 
Example 20
Project: sic   Author: Yanixos   File: enum.py    GNU General Public License v3.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example 21
Project: adh6   Author: bonnetn   File: context.py    GNU General Public License v3.0 5 votes vote down vote up
def log_extra(context: MappingProxyType, **extra_fields):
    admin_login = None
    if context.get(CTX_ADMIN):
        admin_login = context.get(CTX_ADMIN).login

    infos = {
        'request_uuid': context.get(CTX_REQUEST_ID),
        'admin': admin_login,
        'testing': str(context.get(CTX_TESTING) or False),
    }
    return {
        'extra': {**infos, **extra_fields},
    } 
Example 22
Project: pywren-ibm-cloud   Author: pywren   File: cloudpickle.py    Apache License 2.0 5 votes vote down vote up
def save_mappingproxy(self, obj):
            self.save_reduce(types.MappingProxyType, (dict(obj),), obj=obj) 
Example 23
Project: jawfish   Author: war-and-code   File: inspect.py    MIT License 5 votes vote down vote up
def __init__(self, parameters=None, *, return_annotation=_empty,
                 __validate_parameters__=True):
        '''Constructs Signature from the given list of Parameter
        objects and 'return_annotation'.  All arguments are optional.
        '''

        if parameters is None:
            params = OrderedDict()
        else:
            if __validate_parameters__:
                params = OrderedDict()
                top_kind = _POSITIONAL_ONLY

                for idx, param in enumerate(parameters):
                    kind = param.kind
                    if kind < top_kind:
                        msg = 'wrong parameter order: {} before {}'
                        msg = msg.format(top_kind, param.kind)
                        raise ValueError(msg)
                    else:
                        top_kind = kind

                    name = param.name
                    if name is None:
                        name = str(idx)
                        param = param.replace(name=name)

                    if name in params:
                        msg = 'duplicate parameter name: {!r}'.format(name)
                        raise ValueError(msg)
                    params[name] = param
            else:
                params = OrderedDict(((param.name, param)
                                                for param in parameters))

        self._parameters = types.MappingProxyType(params)
        self._return_annotation = return_annotation 
Example 24
Project: Repobot   Author: Desgard   File: _signatures.py    MIT License 5 votes vote down vote up
def parameters(self):
        try:
            return types.MappingProxyType(self._parameters)
        except AttributeError:
            return OrderedDict(self._parameters.items()) 
Example 25
Project: tangent   Author: google   File: funcsigs.py    Apache License 2.0 5 votes vote down vote up
def parameters(self):
    try:
      return types.MappingProxyType(self._parameters)
    except AttributeError:
      return OrderedDict(self._parameters.items()) 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: headerregistry.py    GNU General Public License v3.0 5 votes vote down vote up
def params(self):
        return MappingProxyType(self._params) 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: dataclasses.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, default, default_factory, init, repr, hash, compare,
                 metadata):
        self.name = None
        self.type = None
        self.default = default
        self.default_factory = default_factory
        self.init = init
        self.repr = repr
        self.hash = hash
        self.compare = compare
        self.metadata = (_EMPTY_METADATA
                         if metadata is None or len(metadata) == 0 else
                         types.MappingProxyType(metadata))
        self._field_type = None 
Example 28
Project: NiujiaoDebugger   Author: MrSrc   File: enum.py    GNU General Public License v3.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example 29
Project: discord.py   Author: Rapptz   File: enums.py    MIT License 5 votes vote down vote up
def __members__(cls):
        return types.MappingProxyType(cls._enum_member_map_) 
Example 30
Project: discord.py   Author: Rapptz   File: bot.py    MIT License 5 votes vote down vote up
def cogs(self):
        """Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of cog name to cog."""
        return types.MappingProxyType(self.__cogs)

    # extensions 
Example 31
Project: discord.py   Author: Rapptz   File: bot.py    MIT License 5 votes vote down vote up
def extensions(self):
        """Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of extension name to extension."""
        return types.MappingProxyType(self.__extensions)

    # help command stuff 
Example 32
Project: Alexa-Ecovacs   Author: EtienneMD   File: _compat.py    MIT License 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 33
Project: python-netsurv   Author: sofia-netsurv   File: _compat.py    MIT License 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 34
Project: python-netsurv   Author: sofia-netsurv   File: _compat.py    MIT License 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 35
Project: bob   Author: BobBuildTool   File: stringparser.py    GNU General Public License v3.0 5 votes vote down vote up
def inspect(self):
        return MappingProxyType(self.data) 
Example 36
Project: rekt   Author: dillonhicks   File: utils.py    Apache License 2.0 5 votes vote down vote up
def read_only_dict(mapping):
    return types.MappingProxyType(mapping) 
Example 37
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: __init__.py    MIT License 5 votes vote down vote up
def parameters(self):
        try:
            return types.MappingProxyType(self._parameters)
        except AttributeError:
            return OrderedDict(self._parameters.items()) 
Example 38
Project: unhuman-resources   Author: agajdosi   File: web_request.py    GNU General Public License v3.0 5 votes vote down vote up
def cookies(self) -> Mapping[str, str]:
        """Return request cookies.

        A read-only dictionary-like object.
        """
        raw = self.headers.get(hdrs.COOKIE, '')
        parsed = SimpleCookie(raw)
        return MappingProxyType(
            {key: val.value for key, val in parsed.items()}) 
Example 39
Project: unhuman-resources   Author: agajdosi   File: client_reqrep.py    GNU General Public License v3.0 5 votes vote down vote up
def content_disposition(self) -> Optional[ContentDisposition]:
        raw = self._headers.get(hdrs.CONTENT_DISPOSITION)
        if raw is None:
            return None
        disposition_type, params_dct = multipart.parse_content_disposition(raw)
        params = MappingProxyType(params_dct)
        filename = multipart.content_disposition_filename(params)
        return ContentDisposition(disposition_type, params, filename) 
Example 40
Project: unhuman-resources   Author: agajdosi   File: web_urldispatcher.py    GNU General Public License v3.0 5 votes vote down vote up
def named_resources(self) -> Mapping[str, AbstractResource]:
        return MappingProxyType(self._named_resources) 
Example 41
Project: unhuman-resources   Author: agajdosi   File: _compat.py    GNU General Public License v3.0 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 42
Project: unhuman-resources   Author: agajdosi   File: web_request.py    GNU General Public License v3.0 5 votes vote down vote up
def cookies(self) -> Mapping[str, str]:
        """Return request cookies.

        A read-only dictionary-like object.
        """
        raw = self.headers.get(hdrs.COOKIE, '')
        parsed = SimpleCookie(raw)
        return MappingProxyType(
            {key: val.value for key, val in parsed.items()}) 
Example 43
Project: unhuman-resources   Author: agajdosi   File: client_reqrep.py    GNU General Public License v3.0 5 votes vote down vote up
def content_disposition(self) -> Optional[ContentDisposition]:
        raw = self._headers.get(hdrs.CONTENT_DISPOSITION)
        if raw is None:
            return None
        disposition_type, params_dct = multipart.parse_content_disposition(raw)
        params = MappingProxyType(params_dct)
        filename = multipart.content_disposition_filename(params)
        return ContentDisposition(disposition_type, params, filename) 
Example 44
Project: unhuman-resources   Author: agajdosi   File: web_urldispatcher.py    GNU General Public License v3.0 5 votes vote down vote up
def named_resources(self) -> Mapping[str, AbstractResource]:
        return MappingProxyType(self._named_resources) 
Example 45
Project: unhuman-resources   Author: agajdosi   File: _compat.py    GNU General Public License v3.0 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 46
Project: XMorbid   Author: NMTech0x90   File: enum.py    GNU General Public License v3.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example 47
Project: open-recipe   Author: dspray95   File: _compat.py    The Unlicense 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example 48
Project: openexchangerate   Author: juancarlospaco   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_latest_with_local_base_conversion_decimal(self):
        client = openexchangerate.OpenExchangeRates(
            'DUMMY_API_KEY', use_float=False, local_base='AED')
        HTTPretty.register_uri(HTTPretty.GET, client.ENDPOINT_LATEST,
                               body=self._FIXTURE_LATEST)
        latest_cn = client.latest()

        self.assertIsInstance(latest_cn, tuple)
        self.assertIsInstance(latest_cn.dict, dict)
        self.assertIsInstance(latest_cn.frozendict, frozendict)

        self.assertEqual(latest_cn.dict['AED'], decimal.Decimal('1'))
        self.assertEqual(latest_cn.dict['AFN'], decimal.Decimal('13.97265535'))
        self.assertEqual(latest_cn.dict['ALL'], decimal.Decimal('28.57061253'))
        self.assertEqual(latest_cn.dict['USD'], decimal.Decimal('0.27275373')) 
Example 49
Project: openexchangerate   Author: juancarlospaco   File: openexchangerate.py    GNU General Public License v3.0 5 votes vote down vote up
def _parsed_response(self, response):
        data = loads(response, parse_int=self.tipe,
                     parse_float=self.tipe)['rates']

        if self.local_base:
            data = self._local_conversion(data, self.local_base)

        return namedtuple(
            "OpenExchangeRates", "dict frozendict html namedtuple")(
            data, frozendict(data), self.html(data),
            namedtuple("OpenExchangeRates", data.keys())(*data.values())) 
Example 50
Project: Blockly-rduino-communication   Author: technologiescollege   File: headerregistry.py    GNU General Public License v3.0 5 votes vote down vote up
def params(self):
        return MappingProxyType(self._params)