LoginSignup
1
1

More than 3 years have passed since last update.

gRPC の使い方 (python)

Last updated at Posted at 2020-02-05

参考ページ
Python Quick Start

必要なライブラリーのインストール

sudo python -m pip install grpcio
sudo python -m pip install grpcio-tools

設定ファイル、サーバープログラム、クライアントプログラムの3つが必要です。

設定ファイル

helloworld.proto

syntax = "proto3";

package helloworld;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  rpc SayHello2 (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

サーバープログラム

greeter_server.py
import sys
from concurrent import futures
import logging

import grpc

import helloworld_pb2
import helloworld_pb2_grpc


class Greeter(helloworld_pb2_grpc.GreeterServicer):

    def SayHello(self, request, context):
        sys.stderr.write("*** SayHello ***\n")
        str_out = 'Test Hello, %s!' % request.name
        sys.stderr.write(str_out + "\n")
        return helloworld_pb2.HelloReply(message=str_out)

    def SayHello2(self, request, context):
        sys.stderr.write("*** SayHello2 ***\n")
        str_out = 'Test2 Hello again, %s!' % request.name
        sys.stderr.write(str_out + "\n")
        return helloworld_pb2.HelloReply(message=str_out)


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()


if __name__ == '__main__':
    logging.basicConfig()
    serve()

クライアントプログラム

greeter_client.py
from __future__ import print_function
import logging

import grpc

import helloworld_pb2
import helloworld_pb2_grpc


def run():
    with grpc.insecure_channel('localhost:50051') as channel:
        stub = helloworld_pb2_grpc.GreeterStub(channel)
        response = stub.SayHello(helloworld_pb2.HelloRequest(name='John'))
        print("Greeter client received: " + response.message)
        response = stub.SayHello2(helloworld_pb2.HelloRequest(name='Tom'))
        print("Greeter client received: " + response.message)

if __name__ == '__main__':
    logging.basicConfig()
    run()

gRPC のコードを作成します。

実行前

$ tree
.
├── greeter_client.py
├── greeter_server.py
└── helloworld.proto

スクリプト

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

実行後

$ tree
.
├── greeter_client.py
├── greeter_server.py
├── helloworld_pb2_grpc.py
├── helloworld_pb2.py
└── helloworld.proto

サーバープログラムの起動

python greeter_server.py

クライアントプログラムの実行

$ python greeter_client.py 
Greeter client received: Test Hello, John!
Greeter client received: Test2 Hello again, Tom!

サーバーのコンソールには次のようなメッセージが出ます。

$ python greeter_server.py 
*** SayHello ***
Test Hello, John!
*** SayHello2 ***
Test2 Hello again, Tom!
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1