安装
安装gRPC
pip install grpcio
安装gRPC tools
pip install grpcio-tools
对于python3.6+安装protobuf否则会报错TypeError
# TypeError: __new__() got an unexpected keyword argument 'serialized_options'
pip install -U protobuf
下载样例
# Clone the repository to get the example code:
git clone -b v1.19.0 https://github.com/grpc/grpc
# Navigate to the "hello, world" Python example:
cd grpc/examples/python/helloworld
运行gRPC应用
切换至路径examples/python/helloworld:
- 启动服务端
python greeter_server.p
- 在另一个终端,启动客户端
python greeter_client.py
更新gRPC应用
更新.proto文件
如何在服务端增加一个可供客户端调用的方法?我们使用protocol buffers定义gRPC服务。可以阅读What is gRPC?和gRPC Basics:Python了解更多如果和使用.proto文件定义服务的知识。现在你需要知道的是服务端和客户端都有一个SayHello RPC方法,它从客户端获取一个HelloRequest字段并从服务端返回一个HelloReply,改方法定义如下:
// The greeting service definition
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The reponse message containing the greetings
message HelloReply {
string message = 1;
}
我们更新一下上述内容使Greeter服务有两个方法。在examples/protos/helloworld.proto中加入一个和SayHello有相同request、response类型的方法:SayHelloAgain。更新后的内容如下:
// The greeting service definition
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The reponse message containing the greetings
message HelloReply {
string message = 1;
}
根据新.proto文件生成gRPC代码
为了使应用能使用到新定义的方法我们需要更新gRPC代码
在路径examples/python/helloworld下运行:
python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/helloworld.proto
helloworld_pb2.py包含生成的request和response类, helloworld_pb2_grpc.py包含客户端和服务端类
更新自己的代码并运行应用
现在已经有更新了的服务端和客户端代码,但是我们仍然需要再我们的示例应用中人工撰写部分实现和调用新方法
更新服务端greeter_server.py:
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def SayHelloAgain(self, request, context):
return helloworld_pb2.HelloReply(message='Hello again, %s!' % request.name)
...
更新客户端greeter_client.py:
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message)
response = stub.SayHelloAgain(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message)
运行
- 运行服务
python greeter_server.py
- 在另一个终端,运行客户端
python greeter_client.py
参考:
grpc.io