pip
版本高于 9.0.1$ python -m pip install grpcio==1.38.0 grpcio-status==1.38.0 grpcio-tools==1.38.0 protobuf3-to-dict==0.1.5
参考自GreenPill
这个是用来生成 client & server stub 内容的 Python 文件,stub 暂时先放放。
安装 gRPC tools:
$ python -m pip install grpcio-tools
安装的时候可能会碰到一个错误提示:
command '/usr/bin/clang' failed with exit code 1
这个时候我们可以以如下方式进行安装:
GRPC_PYTHON_BUILD_SYSTEM_OPENSSL=true GRPC_PYTHON_BUILD_SYSTEM_ZLIB=true pip install google-cloud-pubsub==2.1.0
# 参考文档:
# https://stackoverflow.com/questions/64881510/pip-install-on-mac-os-gets-error-command-usr-bin-clang-failed-with-exit-code
我们通过 git 来对示例代码进行获取:
# Clone the repository to get the example code:
$ git clone -b v1.35.0 https://github.com/grpc/grpc
# Navigate to the "hello, world" Python example:
$ cd grpc/examples/python/helloworld
首先进入到 examples/python/helloworld
这个目录下
1、 运行服务器
$ python greeter_server.py
2、 打开另一个窗口,运行客户端
$ python greeter_client.py
这个时候,客户端的 DOS 窗口会打印出一句话。
恭喜,完成!
此时我们可以让 Greeter
服务有两个方法。对 examples/protos/helloworld.proto
文件进行编辑,并且更新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 response message containing the greetings
message HelloReply {
string message = 1;
}
重新生成 gRPC 对应的 Python代码文件:
此时我们切换回 examples/python/helloworld
这个目录:
$ python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/helloworld.proto
python -m grpc_tools.protoc -I$SRC_DIR --python_out=$DST_DIR --grpc_python_out=$DST_DIR $SRC_DIR/helloworld.proto
参数说明:
-I
,并按序查找。这行命令将生成一个 helloworld_pb2.py 及 helloworld_pb2_grpc.py 文件。
如果我们不想生成对应的 helloworld_pb2.py 及 helloworld_pb2_grpc.py 文件,也可以通过下面的方式来进行慢加载:
protos = grpc.protos("helloworld.proto")
services = grpc.services("helloworld.proto")
除非玩的特别溜,否则不推荐使用。
此时我们打开greeter_server.py
文件,参照 SayHello
方法再重新书写一个方法:
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)
...
这里有关 channel 和 stub 的相关概念我们在基础手册中将会介绍
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)
Client 端打印输出:
Greeter client received: Hello, you!
Greeter client received: Hello, me!
参考文章:
下一篇:Python-grpc 基础手册