赞
踩
基于之前的目录结构,微调下:
|- 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
上试试:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。