https://blog.csdn.net/wtt234/article/details/162128299
具体可以先看上次的内容,连接在上面
1.Python 环境准备
# 安装 gRPC Python 包
pip install grpcio grpcio-tools
2.组织结构
pythonAuth/
├── calculator.proto # 复制的 proto 文件
└── client.py # Python 客户端
3.生成 Python gRPC 代码
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. calculator.proto
4.python的client客户端代码
import grpc
import calculator_pb2
import calculator_pb2_grpc
def run():
# 1. 连接到 Go 服务端
channel = grpc.insecure_channel('localhost:50051')
# 2. 创建客户端存根
stub = calculator_pb2_grpc.CalculatorStub(channel)
# 3. 构造请求
request = calculator_pb2.CalcRequest(num1=10, num2=5)
# 4. 调用各个方法
print("=== 调用 Go 服务端计算器 ===")
# 加法
response = stub.Add(request)
print(f"🧮 10 + 5 = {response.result} ({response.message})")
# 减法
response = stub.Subtract(request)
print(f"🧮 10 - 5 = {response.result} ({response.message})")
# 乘法
response = stub.Multiply(request)
print(f"🧮 10 × 5 = {response.result} ({response.message})")
# 除法
response = stub.Divide(request)
print(f"🧮 10 ÷ 5 = {response.result} ({response.message})")
# 5. 测试除零错误
try:
request_zero = calculator_pb2.CalcRequest(num1=10, num2=0)
response = stub.Divide(request_zero)
print(f"🧮 10 ÷ 0 = {response.result}")
except grpc.RpcError as e:
print(f"❌ 10 ÷ 0 报错: {e.details()} (code: {e.code()})")
if __name__ == '__main__':
run()
5.运行查看效果
[pythonAuth]# python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. calculator.proto
=======================================
[pythonAuth]# python client.py
=== 调用 Go 服务端计算器 ===
🧮 10 + 5 = 15.0 (成功)
🧮 10 - 5 = 5.0 (成功)
🧮 10 × 5 = 50.0 (成功)
🧮 10 ÷ 5 = 2.0 (成功)
❌ 10 ÷ 0 报错: 除数不能为0 (code: StatusCode.INVALID_ARGUMENT)
[pythonAuth]#
6.项目最终文件效果

