当前位置:   article > 正文

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

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

续之前《【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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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

SERVER_CONFIG = {
    "host_port": "[::]:50052"
}
  • 1
  • 2
  • 3

接着服务端接口业务代码(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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

最后, 入口文件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()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

启动服务端服务:

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/492232
推荐阅读
相关标签
  

闽ICP备14008679号