grpc官方文档实验与翻译(python版)

来源:互联网 发布:js里的window.onload 编辑:程序博客网 时间:2024/06/09 15:04

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 greetingsmessage 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

(既要实习又要发论文的日子好难熬~.~)












0 1