- Python 安装, 下载后直接安装
2. Pip 安装
$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py # 下载安装脚本
$ sudo python get-pip.py # 运行安装脚本
3. grpc安装
gRPC 的安装:
$ pip install grpcio
安装 ProtoBuf 相关的 python 依赖库:
$ pip install protobuf
安装 python grpc 的 protobuf 编译工具:
$ pip install grpcio-tools
4. grpc简单使用
(1) proto 文件
(2) 生成grpc和protobuf的python文件
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./person.proto
(3) 客户端
# -*- coding: utf-8 -*-
import grpc
import person_pb2_grpc
import person_pb2
def run():
conn = grpc.insecure_channel('localhost:1020')
client = person_pb2_grpc.GreeterStub(channel=conn)
response = client.SayHello(person_pb2.HelloRequest(name="Python"))
print("received : ", response.message)
if __name__ == '__main__':
run()
(4) 服务器端
fromconcurrentimportfutures
importtime
importgrpc
importperson_pb2
importperson_pb2_grpc
#实现proto文件中定义的GreeterServicer
classGreeter(person_pb2_grpc.GreeterServicer):
#实现proto文件中定义的rpc调用
defSayHello(self,request,context):
returnperson_pb2.HelloReply(message='hello{msg}'.format(msg=request.name))
defserve():
server=grpc.server(futures.ThreadPoolExecutor(max_workers=10))
person_pb2_grpc.add_GreeterServicer_to_server(Greeter(),server)
server.add_insecure_port('[::]:1020')
server.start()
try:
whileTrue:
time.sleep(60*60*24)#onedayinseconds
exceptKeyboardInterrupt:
server.stop(0)
if__name__=='__main__':
serve()
参考:
pip安装 https://www.runoob.com/w3cnote/python-pip-install-usage.html
grpc安装 https://blog.csdn.net/circleyuanquan/article/details/82803814
grpc使用 https://www.jianshu.com/p/43fdfeb105ff