要調用RPC接口,python提供了一個框架grpc,這是google開源的
rpc相關文檔:
https://grpc.io/docs/tutorials/basic/python.html
需要安裝的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 grpcimport 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接口的實例詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答