【gRPC】Python建立服务端含接口映射

本文详细介绍了如何使用gRPC框架,包括protoc编译、Python接口编写、配置服务端地址以及服务反射功能。作者展示了如何在example目录下创建服务、处理请求并启动GRPC服务,最后通过Postman进行测试。
摘要由CSDN通过智能技术生成

续之前《【gRPC】protoc文件转py文件》

基于之前的目录结构,微调下:

|- example    # 新增
   |- service
      |- api
        |- User.py
      |- configs.py
|- example_proto
   |- core
      |- user.proto
|- proto_output
   |- core # 续上文转化后的结果
      |- user_pb2.py
      |- user_pb2.pyi
      |- user_pb2_grpc.py

|- grpc_service.py # 服务端服务入口文件
|- ProtoToPy.bat

先搞个配置吧~
example/service/configs.py文件:

SERVER_CONFIG = {
    "host_port": "[::]:50052"
}

接着服务端接口业务代码(example/service/api/User.py):

import grpc

from proto_output.core import user_pb2
from proto_output.core import user_pb2_grpc


class UserService(user_pb2_grpc.UserServiceServicer):
    def AddUser(self, request: user_pb2.AddUserRequest, context: grpc.ServicerContext):
        print("from: ", context.peer())
        print("接收数据->username: ", request.username)
        print("接收数据->age: ", request.age)
        return user_pb2.AddUserResponse(uid=999)

最后, 入口文件grpc_service.py

import grpc
from concurrent.futures import ThreadPoolExecutor
from grpc_reflection.v1alpha import reflection

from example.service.configs import SERVER_CONFIG
from example.service.api import User
from proto_output.core import user_pb2
from proto_output.core import user_pb2_grpc


if __name__ == '__main__':
    server = grpc.server(ThreadPoolExecutor(max_workers=10))
    server.add_insecure_port(SERVER_CONFIG['host_port'])  # 添加监听端口

    user_pb2_grpc.add_UserServiceServicer_to_server(User.UserService(), server)

    # 开启服务端反射
    service_name = user_pb2.DESCRIPTOR.services_by_name.keys()[0]
    service_names = (
        user_pb2.DESCRIPTOR.services_by_name[service_name].full_name,
        reflection.SERVICE_NAME,
    )
    reflection.enable_server_reflection(service_names, server)

    # 启动GRPC服务
    server.start()
    print("grpc服务已启动: %s" % SERVER_CONFIG['host_port'])
    server.wait_for_termination()

启动服务端服务:

(grpc-venv) C:\Users\dev\Desktop\text>python main.py
grpc服务已启动: [::]:50052

postman上试试:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陀螺蚁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值