4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

gRPC でテキストと画像を取得 (python)

Last updated at Posted at 2020-02-07

参考ページ
gRPCとProtocol Buffersによるアプリケーション間通信 / Python

$ tree
.
├── in01.jpg
├── simple_client.py
├── simple.proto
└── simple_server.py

設定ファイル

simple.proto
syntax = "proto3";

package simple;

//RPCインタフェースの定義
service SimpleService{
  rpc SimpleSend (SimpleRequest) returns (SimpleReply) {}
}

//リクエスト
message SimpleRequest{
}

//レスポンス
message SimpleReply{
  string text = 1;
  string image = 2;
}

サーバープログラム

simple_server.py
#! /usr/bin/python
#
import time
import grpc
import simple_pb2
import simple_pb2_grpc
import base64
from concurrent import futures

# シンプルサービスサーバーの定義
class SimpleServiceServicer(simple_pb2_grpc.SimpleServiceServicer):
	# 初期化
	def __init__(self):
		pass

	# 受信時の処理
	def SimpleSend(self, request, context):
		text = 'Hello Everybody!'
		b64 = base64.encodebytes(open('in01.jpg', 'rb').read()).decode('utf8')
		return simple_pb2.SimpleReply(text=text, image=b64)

# サーバーの開始
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
simple_pb2_grpc.add_SimpleServiceServicer_to_server(SimpleServiceServicer(), server)
server.add_insecure_port('[::]:50051')
server.start()
print('サーバーの開始')

# 待機
try:
	while True:
		time.sleep(3600)
except KeyboardInterrupt:
   # サーバーの停止
	server.stop(0)

クライアントプログラム

simple_client.py
#! /usr/bin/python
#
import grpc
import simple_pb2
import simple_pb2_grpc
import base64
import sys
#
# サーバーとの接続
with grpc.insecure_channel('localhost:50051') as channel:
	stub = simple_pb2_grpc.SimpleServiceStub(channel)

	# データの取得
	response = stub.SimpleSend(simple_pb2.SimpleRequest())
	print('text:', response.text)
	img_file = 'client.jpg'
	with open(img_file, mode='wb') as f:
		f.write(base64.b64decode(response.image))
		sys.stderr.write(img_file + "  is saved.\n")

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

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

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

/simple_server.py

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

$ ./simple_client.py 
text: Hello Everybody!
client.jpg  is saved.
4
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?