python - 如何从 protobuf 生成 python 类文件

标签 python protocol-buffers grpc

我正在尝试将大量结构化数据从 Java 传输到 Python。这包括许多以某种形式相互关联的对象。当我在我的 Python 代码中收到它们时,使用 protobuf 提供的类型是非常丑陋的。当尝试对类型使用自动完成时,我的 VIM IDE 崩溃了,PyCharm 没有完成任何东西,而且它们没有为不同的类型。

在 python 中处理 protobuf 消息时,有没有办法获得 IDE 支持?我正在查看 20 多种处理复杂消息的方法,如果没有 IDE 支持,我还不如使用记事本进行编码。

enter image description here

我知道 protobuf 正在使用元类(虽然我不知道他们为什么这样做)。也许有一种方法可以从该数据生成 python 类文件,或者可能有类似于 typescript typing files 的东西.

我可能误用了 protobuf 吗?我相信我会以一种可以跨语言使用的方式来描述我的领域模型。在 Java 中,我对生成的类很满意,我可以轻松地使用它们。我是否应该使用类似 swagger.io 的东西?相反?

最佳答案

如果您使用的是最新的 Python (3.7+),那么 https://github.com/danielgtaylor/python-betterproto (免责声明:我是作者)将生成非常干净的 Python 数据类作为输出,这将为您提供正确的输入和 IDE 完成支持。

例如,这个输入:

syntax = "proto3";

package hello;

// Greeting represents a message you can tell a user.
message Greeting {
  string message = 1;
}

将生成以下输出:

# Generated by the protocol buffer compiler.  DO NOT EDIT!
# sources: hello.proto
# plugin: python-betterproto
from dataclasses import dataclass

import betterproto


@dataclass
class Hello(betterproto.Message):
    """Greeting represents a message you can tell a user."""

    message: str = betterproto.string_field(1)

一般来说,此插件的输出模仿 *.proto 输入,如果您碰巧跳转到消息或字段的定义,则非常容易阅读。对我个人而言,相对于官方 Google 编译器插件,这是一个 巨大 改进,并且还支持开箱即用的 async gRPC。

关于python - 如何从 protobuf 生成 python 类文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49755565/

相关文章:

hadoop - 映射减少作业 : Protobuf related error

cpp异步服务器中的gRPC多个服务

node.js - 如何处理流开始后 grpc-node 中发生的网络错误?

python - Python 中的 for 循环中的 continue 和 pass 之间有区别吗?

python - matplotlib:使用 fill_between 制作彩色三角形

python - 从向量创建字符串

python - 简单的python程序陷入无限循环

c++ - 在外部消息中包含预编码的 Protocol Buffer 消息

c++ - 如何根据谷歌 Protocol Buffer 的要求定义重复字段?

android - 使用 ndk arm-linux-androideabi-clang++ 编译器为 android 构建 grpc C++