pip install grpcio
pip install grpcio_tools
pip install protobuf
1.安装好了必要的模块和工具(编译器)之后,我们就可以根据proto协议文件生成所需的模块和方法,比如我们要测试的协议文件是consumer.proto,那我们cmd命令行打开,进入到存放.proto文件目录下,敲下面的命令:
python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. consumer.proto
2.敲完命令会生成两个文件:
consumer_pb2.py
consumer_pb2_grpc.py
可以拖到你写grpc接口测试的项目里面,方便自己后面去使用(没有.proto文件的找开发要,或者自己去你们项目github里面去拉下来)
import consumer_pb2
import consumer_pb2_grpc
import grpc
def call_service_test(**kwargs):
# 使用with语法保证channel自动close
with grpc.insecure_channel('127.0.0.1:8080') as grpc_connect:
# 客户端通过stub来实现rpc通信
connects = consumer_pb2_grpc.GatewayStub(grpc_connect)
# connects.测试接口(counsumer_pb2.proto文件内定义好的入参(请求参数))
response = connects.CallService(consumer_pb2.CallServiceReq(**kwargs))
return response
if __name__ == '__main__':
body_data = {"request_id": "ff77a251-85cd-44d7-bae9-cdd4fec41136",
"service_id": "05fa4d29-f664-4ed4-91a1-70839f329a1a",
"method": "Hello",
"args": "Hello",
"tx_hash": "Hello",
"sender": "Hello",
"signature": {
"sig": "Hello",
"pubkey": {
"type": 0,
"value": "Hello"
}}}
res = call_service_test(**body_data)
print(res)