当前位置: 移动技术网 > IT编程>脚本编程>Python > 对python调用RPC接口的实例详解

对python调用RPC接口的实例详解

2019年01月07日  | 移动技术网IT编程  | 我要评论

贵阳多地大雨冰雹,m美女裤裆凸起照片,澄城二手房出售

要调用rpc接口,python提供了一个框架grpc,这是google开源的

rpc相关文档:

需要安装的python包如下:

1.grpc安装

pip install grpcio

2.grpc的python protobuf相关的编译工具

pip install grpcio-tools

3.protobuf相关python依赖库

pip install protobuf

4.一些常见原型的生成python类的集合:

pip install googleapis-common-protos

编译protobuf文件:使用以下命令生成python代码:

python3 -m grpc_tools.protoc -i<目标路径目录> --python_out=. --grpc_python_out=<目标文件所在目录路径> <目标文件data.proto>

python3 -m grpc_tools.protoc -i. --python_out=. --grpc_python_out=. data.proto

注意:protobuf文件,为定义服务接口代码文件,这里是data.proto

会生成:data_pb2.py 与 data_pb2_grpc.py

data_pb2.py是服务接口映射

data_pb2_grpc.py方法映射

protobuf内容示例:

syntax = "proto3";
package grpcdemo;

message hellorequest {
 string name = 1;
}

message helloreply {
 string message = 1;
}


service grpc {
 rpc sayhello (hellorequest) returns (helloreply) {}
}

接口调用内容示例:

# -*- coding: utf-8 -*-
import grpc
import data_pb2,data_pb2_grpc

_host = 'localhost'
_port = '8080'

def run():
 conn = grpc.insecure_channel(_host + ':' + _port)
 client = data_pb2_grpc.grpcstub(channel=conn)
 response = client.sayhello(data_pb2.hellorequest(name='hello,world!'))
 print("received: " + response.text)

if __name__ == '__main__':
 run()

以上这篇对python调用rpc接口的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网