1. 程式人生 > >grpc官方文件實驗與翻譯(python版)

grpc官方文件實驗與翻譯(python版)

tensorflow分散式與tensorflow serving底層通訊都是是用的grpc,所以就看了一下grpc的基本用法(python版)

首先是環境的安裝,先要更新pip到version8或者以上

$ python -m pip install --upgrade pip
為了不影響自帶的python環境所以我重新建立了個環境來實驗,我的python環境是conda所以用conda重新建立了個python3.5的環境
$conda create --name py35tf python=3.5
$source activate py35tf
如果不是使用conda的小夥伴可以安裝virtualenv來完成,可以使用conda env list來檢視自己創立的環境

接下來還是工具的安裝

$ python -m pip install grpcio
$ python -m pip install grpcio-tools
$ pip install protobuf
protobuf其實是google自己開發的類似xml一類的序列化的工具,等會要用到,所以也要安裝

接下來我們首先試著使用一下官方給予的example,然後再按照自己的需求更新proto檔案 服務端和客戶端的python檔案

從github上clone官方教程

$ # Clone the repository to get the example code:
$ git clone https://github.com/grpc/grpc
$ # Navigate to the "hello, world" Python example:
$ cd grpc/examples/python/helloworld
然後執行greeter_server.py和greeter_client.py,為了更好的觀察,我在執行server.時加了&讓它後臺執行
$ python greeter_server.py &
$ python greeter_client.py

這時候視窗會輸出Greeter client received:Hello,you!

然後使用jobs檢視一下服務端的程序ID,再使用kill ID直接帶走服務端程序,準備寫一個自己定義的服務了

首先需要修改proro檔案來定義服務,主要是添加了SayHelloAgain

syntax = "proto3";
// 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;
}
官方文件中沒有第一句,編譯成python時老是報錯,接下來開始編譯成python介面
$ python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./helloworld.proto
這樣就把兩個py介面檔案都更新好了,現在更新服務端檔案,原來Greeter類下只有SayHello一個方法,現在新增一下SayHelloAgain
def SayHelloAgain(self, request, context):
    return helloworld_pb2.HelloReply(message='Hello again, %s!' % request.name)
現在再更改一下客戶端的呼叫介面,新增呼叫和輸出的程式碼
  response = stub.SayHelloAgain(helloworld_pb2.HelloRequest(name='you'))
  print("Greeter client received: " + response.message)
完成後再執行服務端和客戶端,來個截圖收工,有空再試著使用tensorflow serving

(既要實習又要發論文的日子好難熬~.~)