Skip to content

Instantly share code, notes, and snippets.

@craftslab
Last active January 29, 2022 12:21
Show Gist options
  • Save craftslab/1f073fdbd88e922d4f9611d806c81362 to your computer and use it in GitHub Desktop.
Save craftslab/1f073fdbd88e922d4f9611d806c81362 to your computer and use it in GitHub Desktop.
python grpc

Install

pip install grpcio
pip install grpcio-tools

Build

python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. helloworld.proto

Run

# Run gRPC server
python server.py

# Run gRPC client
python client.py

Reference

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
def run():
channel = grpc.insecure_channel("127.0.0.1:9090")
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name="World"))
print("Greeter client received: " + response.message)
response = stub.SayHelloAgain(helloworld_pb2.HelloRequest(name="World again"))
print("Greeter client received: " + response.message)
if __name__ == "__main__":
run()
syntax = "proto3";
package helloworld;
// 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;
}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
from concurrent import futures
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message="Hello {msg}".format(msg=request.name))
def SayHelloAgain(self, request, context):
return helloworld_pb2.HelloReply(message="Hello {msg}".format(msg=request.name))
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port("[::]:9090")
server.start()
server.wait_for_termination()
if __name__ == "__main__":
serve()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment