client.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright 2019 The 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. """This example handles rich error status in client-side."""
  15. from __future__ import print_function
  16. import logging
  17. from google.rpc import error_details_pb2
  18. import grpc
  19. from grpc_status import rpc_status
  20. from examples.protos import helloworld_pb2
  21. from examples.protos import helloworld_pb2_grpc
  22. _LOGGER = logging.getLogger(__name__)
  23. def process(stub):
  24. try:
  25. response = stub.SayHello(helloworld_pb2.HelloRequest(name='Alice'))
  26. _LOGGER.info('Call success: %s', response.message)
  27. except grpc.RpcError as rpc_error:
  28. _LOGGER.error('Call failure: %s', rpc_error)
  29. status = rpc_status.from_call(rpc_error)
  30. for detail in status.details:
  31. if detail.Is(error_details_pb2.QuotaFailure.DESCRIPTOR):
  32. info = error_details_pb2.QuotaFailure()
  33. detail.Unpack(info)
  34. _LOGGER.error('Quota failure: %s', info)
  35. else:
  36. raise RuntimeError('Unexpected failure: %s' % detail)
  37. def main():
  38. # NOTE(gRPC Python Team): .close() is possible on a channel and should be
  39. # used in circumstances in which the with statement does not fit the needs
  40. # of the code.
  41. with grpc.insecure_channel('localhost:50051') as channel:
  42. stub = helloworld_pb2_grpc.GreeterStub(channel)
  43. process(stub)
  44. if __name__ == '__main__':
  45. logging.basicConfig()
  46. main()