src/python/grpcio/grpc/aio/_metadata.py
Go to the documentation of this file.
1 # Copyright 2020 gRPC authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """Implementation of the metadata abstraction for gRPC Asyncio Python."""
15 from collections import OrderedDict
16 from collections import abc
17 from typing import Any, Iterator, List, Tuple, Union
18 
19 MetadataKey = str
20 MetadataValue = Union[str, bytes]
21 
22 
23 class Metadata(abc.Mapping):
24  """Metadata abstraction for the asynchronous calls and interceptors.
25 
26  The metadata is a mapping from str -> List[str]
27 
28  Traits
29  * Multiple entries are allowed for the same key
30  * The order of the values by key is preserved
31  * Getting by an element by key, retrieves the first mapped value
32  * Supports an immutable view of the data
33  * Allows partial mutation on the data without recreating the new object from scratch.
34  """
35 
36  def __init__(self, *args: Tuple[MetadataKey, MetadataValue]) -> None:
37  self._metadata = OrderedDict()
38  for md_key, md_value in args:
39  self.add(md_key, md_value)
40 
41  @classmethod
42  def from_tuple(cls, raw_metadata: tuple):
43  if raw_metadata:
44  return cls(*raw_metadata)
45  return cls()
46 
47  def add(self, key: MetadataKey, value: MetadataValue) -> None:
48  self._metadata.setdefault(key, [])
49  self._metadata[key].append(value)
50 
51  def __len__(self) -> int:
52  """Return the total number of elements that there are in the metadata,
53  including multiple values for the same key.
54  """
55  return sum(map(len, self._metadata.values()))
56 
57  def __getitem__(self, key: MetadataKey) -> MetadataValue:
58  """When calling <metadata>[<key>], the first element of all those
59  mapped for <key> is returned.
60  """
61  try:
62  return self._metadata[key][0]
63  except (ValueError, IndexError) as e:
64  raise KeyError("{0!r}".format(key)) from e
65 
66  def __setitem__(self, key: MetadataKey, value: MetadataValue) -> None:
67  """Calling metadata[<key>] = <value>
68  Maps <value> to the first instance of <key>.
69  """
70  if key not in self:
71  self._metadata[key] = [value]
72  else:
73  current_values = self.get_all(key)
74  self._metadata[key] = [value, *current_values[1:]]
75 
76  def __delitem__(self, key: MetadataKey) -> None:
77  """``del metadata[<key>]`` deletes the first mapping for <key>."""
78  current_values = self.get_all(key)
79  if not current_values:
80  raise KeyError(repr(key))
81  self._metadata[key] = current_values[1:]
82 
83  def delete_all(self, key: MetadataKey) -> None:
84  """Delete all mappings for <key>."""
85  del self._metadata[key]
86 
87  def __iter__(self) -> Iterator[Tuple[MetadataKey, MetadataValue]]:
88  for key, values in self._metadata.items():
89  for value in values:
90  yield (key, value)
91 
92  def get_all(self, key: MetadataKey) -> List[MetadataValue]:
93  """For compatibility with other Metadata abstraction objects (like in Java),
94  this would return all items under the desired <key>.
95  """
96  return self._metadata.get(key, [])
97 
98  def set_all(self, key: MetadataKey, values: List[MetadataValue]) -> None:
99  self._metadata[key] = values
100 
101  def __contains__(self, key: MetadataKey) -> bool:
102  return key in self._metadata
103 
104  def __eq__(self, other: Any) -> bool:
105  if isinstance(other, self.__class__):
106  return self._metadata == other._metadata
107  if isinstance(other, tuple):
108  return tuple(self) == other
109  return NotImplemented # pytype: disable=bad-return-type
110 
111  def __add__(self, other: Any) -> 'Metadata':
112  if isinstance(other, self.__class__):
113  return Metadata(*(tuple(self) + tuple(other)))
114  if isinstance(other, tuple):
115  return Metadata(*(tuple(self) + other))
116  return NotImplemented # pytype: disable=bad-return-type
117 
118  def __repr__(self) -> str:
119  view = tuple(self)
120  return "{0}({1!r})".format(self.__class__.__name__, view)
grpc.aio._metadata.Metadata.delete_all
None delete_all(self, MetadataKey key)
Definition: src/python/grpcio/grpc/aio/_metadata.py:83
http2_test_server.format
format
Definition: http2_test_server.py:118
grpc.aio._metadata.Metadata.__getitem__
MetadataValue __getitem__(self, MetadataKey key)
Definition: src/python/grpcio/grpc/aio/_metadata.py:57
get
absl::string_view get(const Cont &c)
Definition: abseil-cpp/absl/strings/str_replace_test.cc:185
grpc.aio._metadata.Metadata.__init__
None __init__(self, *Tuple[MetadataKey, MetadataValue] args)
Definition: src/python/grpcio/grpc/aio/_metadata.py:36
grpc::testing::sum
double sum(const T &container, F functor)
Definition: test/cpp/qps/stats.h:30
grpc.aio._metadata.Metadata.add
None add(self, MetadataKey key, MetadataValue value)
Definition: src/python/grpcio/grpc/aio/_metadata.py:47
grpc.aio._metadata.Metadata.get_all
List[MetadataValue] get_all(self, MetadataKey key)
Definition: src/python/grpcio/grpc/aio/_metadata.py:92
map
zval * map
Definition: php/ext/google/protobuf/encode_decode.c:480
grpc.aio._metadata.Metadata.__repr__
str __repr__(self)
Definition: src/python/grpcio/grpc/aio/_metadata.py:118
grpc.aio._metadata.Metadata.from_tuple
def from_tuple(cls, tuple raw_metadata)
Definition: src/python/grpcio/grpc/aio/_metadata.py:42
grpc.aio._metadata.Metadata.__eq__
bool __eq__(self, Any other)
Definition: src/python/grpcio/grpc/aio/_metadata.py:104
grpc.aio._metadata.Metadata.__len__
int __len__(self)
Definition: src/python/grpcio/grpc/aio/_metadata.py:51
grpc.aio._metadata.Metadata._metadata
_metadata
Definition: src/python/grpcio/grpc/aio/_metadata.py:37
xds_manager.items
items
Definition: xds_manager.py:55
grpc.aio._metadata.Metadata
Definition: src/python/grpcio/grpc/aio/_metadata.py:23
grpc.aio._metadata.Metadata.__contains__
bool __contains__(self, MetadataKey key)
Definition: src/python/grpcio/grpc/aio/_metadata.py:101
grpc.aio._metadata.Metadata.__iter__
Iterator[Tuple[MetadataKey, MetadataValue]] __iter__(self)
Definition: src/python/grpcio/grpc/aio/_metadata.py:87
values
std::array< int64_t, Size > values
Definition: abseil-cpp/absl/container/btree_benchmark.cc:608
grpc.aio._metadata.Metadata.__delitem__
None __delitem__(self, MetadataKey key)
Definition: src/python/grpcio/grpc/aio/_metadata.py:76
grpc.aio._metadata.Metadata.set_all
None set_all(self, MetadataKey key, List[MetadataValue] values)
Definition: src/python/grpcio/grpc/aio/_metadata.py:98
grpc.aio._metadata.Metadata.__setitem__
None __setitem__(self, MetadataKey key, MetadataValue value)
Definition: src/python/grpcio/grpc/aio/_metadata.py:66
grpc.aio._metadata.Metadata.__add__
'Metadata' __add__(self, Any other)
Definition: src/python/grpcio/grpc/aio/_metadata.py:111


grpc
Author(s):
autogenerated on Thu Mar 13 2025 02:58:27