python - 如何在 Python 的 proto 文件中使用嵌套类型?
问题描述
我已经对 grpc-python 进行了实验,并且能够重现 HelloWorld 以及我在 Internet 上找到的一些其他示例。但是,我不清楚如何在 proto 文件中使用嵌套类型。
syntax = "proto3";
import "google/protobuf/timestamp.proto";
/*
UUID
*/
message Uuid
{
string value = 1;
}
message StatRequest
{
// File UUID
Uuid uuid = 1;
}
message StatReply
{
Data data = 1;
message Data
{
google.protobuf.Timestamp create_datetime = 1;
}
}
我已经使用 protoc 生成了文件,并且我知道如何使用简单类型。
但是,我很难发送和接收这些复杂类型。
我不知道如何引用它们。
这是服务器代码:
from concurrent import futures
import threading
import time
import grpc
import work_pb2
import work_pb2_grpc
class Listener(work_pb2_grpc.FileServicer):
"""The listener function implements the rpc call as described in the .proto file"""
def __init__(self):
self.counter = 0
self.last_print_time = time.time()
def __str__(self):
return self.__class__.__name__
# HERE IS ONE PROBLEM I THINK
def stat(self, request, context):
return work_pb2.StatReply()
def serve():
"""The main serve function of the server.
This opens the socket, and listens for incoming grpc conformant packets"""
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
work_pb2_grpc.add_FileServicer_to_server(Listener(), server)
server.add_insecure_port("[::]:9999")
server.start()
try:
while True:
print("Server Running : threadcount %i" % (threading.active_count()))
time.sleep(10)
except KeyboardInterrupt:
print("KeyboardInterrupt")
server.stop(0)
if __name__ == "__main__":
serve()
和客户:
import os
import time
import grpc
import work_pb2
import work_pb2_grpc
def run():
with grpc.insecure_channel("localhost:9999") as channel:
stub = work_pb2_grpc.FileStub(channel)
print(stub)
while True:
# HOW DO I PRINT THE MESSAGES FROM THE SERVER ?
# I am not sure how to reference the complex type defined in my proto
# This works with non-nested types
# response = stub.stat(work_pb2.StatReply)
# print(response)
return
def close(channel):
"Close the channel"
channel.close()
if __name__ == "__main__":
run()
任何建议,帮助将不胜感激,谢谢。
解决方案
推荐阅读
- python - 未找到测试夹具“postgres”
- ios - Xcode 可以分发 iOS 应用程序但 altool 不起作用
- php - 根据子对象数组值对关联/多维数组进行排序
- lasso-regression - 我无法使用 Sklearn 库通过 Lasso Regression 获得我想要的输出
- xslt - 如何在 XSLT 中检查 NaN?
- delphi-10.3-rio - Delphi 10.3.3 FireDAC FDConnection.GetTableNames Interbase
- javascript - 使用对象日期属性对数组进行排序
- php - 如何在两个日期之间创建数组循环
- oracle - 我想将用户定义的数据类型从 ORACLE 转换为有效的 POSTGRE 用户定义数据?
- git - git filter-branch 不会删除我想要的所有文件