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

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












  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值