_metadata.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright 2017 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. """API metadata conversion utilities."""
  15. import collections
  16. _Metadatum = collections.namedtuple('_Metadatum', (
  17. 'key',
  18. 'value',
  19. ))
  20. def _beta_metadatum(key, value):
  21. beta_key = key if isinstance(key, (bytes,)) else key.encode('ascii')
  22. beta_value = value if isinstance(value, (bytes,)) else value.encode('ascii')
  23. return _Metadatum(beta_key, beta_value)
  24. def _metadatum(beta_key, beta_value):
  25. key = beta_key if isinstance(beta_key, (str,)) else beta_key.decode('utf8')
  26. if isinstance(beta_value, (str,)) or key[-4:] == '-bin':
  27. value = beta_value
  28. else:
  29. value = beta_value.decode('utf8')
  30. return _Metadatum(key, value)
  31. def beta(metadata):
  32. if metadata is None:
  33. return ()
  34. else:
  35. return tuple(_beta_metadatum(key, value) for key, value in metadata)
  36. def unbeta(beta_metadata):
  37. if beta_metadata is None:
  38. return ()
  39. else:
  40. return tuple(
  41. _metadatum(beta_key, beta_value)
  42. for beta_key, beta_value in beta_metadata)