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

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