document:
my version:
Python 3.6.8
grpcio 1.25.0
grpcio-tools 1.25.0
nginx version: nginx/1.14.0
install:
pip3 install grpcio
pip3 install grpcio grpcio-tools googleapis-common-protos
pycharm:
protoc 准备工具
gen
create file msg.proto
syntax = "proto3"; // 规定语法 proto3 service MsgService { rpc GetMsg (MsgRequest) returns (MsgResponse){} } // service 规定服务的关键字 service单一请求单一回应的服务 message MsgRequest { string name = 1; }//定义括号里的初始值 type 可以是 int32,int64,double,float message MsgResponse { string msg = 1; }//定义括号里的初始值
comand gen my need server and client of python' code
python -m grpc_tools.protoc -I . --python_out=. --grpc_python_out=.msg.proto
and from msg.proto
now you can look two files : msg_pb2.py and msg_pb2_grpc.py
msg_pb2.py contain client call server’code
msg_pb2_grpc.py usually contains the server's own code
use
and create a rpc server for client call
you need inherit class and rewrite function
use_server.py
import grpc import msg_pb2 #response 的一些方法 clinet import msg_pb2_grpc #server from concurrent import futures import time _ONE_DAY_IN_SECONDS = 60 * 60 * 24 #定义一天的秒数 class MsgServicer(msg_pb2_grpc.MsgServiceServicer): def GetMsg(self, request, context): print("Received name: %s" % request.name) return msg_pb2.MsgResponse(msg='Hello, %s!' % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) msg_pb2_grpc.add_MsgServiceServicer_to_server(MsgServicer(), server) #定义的服务 server.add_insecure_port('[::]:50051') server.start() #阻塞主进程 子进程不会退出 try: while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: server.stop(0) if __name__ == '__main__': serve()
start command
python3 use_server.py
now you can call rpc ,Wait and see
create a client call code !
use client call
import grpc import msg_pb2 import msg_pb2_grpc def send_hello(name): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel('localhost:50051') as channel: stub = msg_pb2_grpc.MsgServiceStub(channel) response = stub.GetMsg(msg_pb2.MsgRequest(name=name)) print("Client received: " + response.msg) if __name__ == '__main__': send_hello("haha")