Skip to content

Python客户端

cyshi edited this page Nov 17, 2016 · 1 revision

本文档包括:

  • 特性
  • 安装
  • 使用

特性

当前支持的特性:

  • 支持同步调用
  • 支持超时控制

关键类:

  • sofa.pbrpc.client.Channel
  • sofa.pbrpc.client.Controller
  • sofa.pbrpc.client.Error
  • sofa.pbrpc.client.TimeoutError (该异常为sofa.pbrpc.client.Error的子类)

如果调用过程出现错误,则会抛出异常,异常类型包括:

  • 超时,抛出sofa.pbrpc.client.TimeoutError
  • 其他错误,抛出sofa.pbrpc.client.Error或者其他Exception子类

如果远程server端通过controller.SetFailed(reason)设置了调用失败,则在client端:

  • 调用本身返回None
  • controller.Failed()返回True
  • controller.ErrorText()返回错误信息

安装

参见 https://github.com/BaiduPS/sofa-pbrpc/blob/master/python

使用

参见 https://github.com/BaiduPS/sofa-pbrpc/blob/master/python/sample

使用样例:

from sofa.pbrpc import client
import echo_service_pb2
import sys

# Create service stub.
channel = client.Channel("localhost:8080")
service = echo_service_pb2.EchoServer_Stub(channel)

# Create controller.
# We set timeout to 1.5 seconds by controller.SetTimeout() method.
controller = client.Controller()
controller.SetTimeout(1.5)

# Prepare request.
request = echo_service_pb2.EchoRequest()
request.message = 'Hello World'

# Call method.
try:
  response = service.Echo(controller, request)
except client.TimeoutError:
  print "ERROR: RPC timeout"
  sys.exit(1)
except Exception as e:
  print "ERROR: RPC fail: %s" % e
  sys.exit(1)

# Check remote failure.
if controller.Failed():
  print "ERROR: Remote fail: %s" % controller.ErrorText()
  sys.exit(1)

# OK, print response.
print "Response:\n\n%s" % response
Clone this wiki locally