_metadata.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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(
  17. "_Metadatum",
  18. (
  19. "key",
  20. "value",
  21. ),
  22. )
  23. def _beta_metadatum(key, value):
  24. beta_key = key if isinstance(key, (bytes,)) else key.encode("ascii")
  25. beta_value = value if isinstance(value, (bytes,)) else value.encode("ascii")
  26. return _Metadatum(beta_key, beta_value)
  27. def _metadatum(beta_key, beta_value):
  28. key = beta_key if isinstance(beta_key, (str,)) else beta_key.decode("utf8")
  29. if isinstance(beta_value, (str,)) or key[-4:] == "-bin":
  30. value = beta_value
  31. else:
  32. value = beta_value.decode("utf8")
  33. return _Metadatum(key, value)
  34. def beta(metadata):
  35. if metadata is None:
  36. return ()
  37. else:
  38. return tuple(_beta_metadatum(key, value) for key, value in metadata)
  39. def unbeta(beta_metadata):
  40. if beta_metadata is None:
  41. return ()
  42. else:
  43. return tuple(
  44. _metadatum(beta_key, beta_value)
  45. for beta_key, beta_value in beta_metadata
  46. )