如何从 protobuf 生成 python class 文件
How to generate python class files from protobuf
我正在尝试将大量结构化数据从 Java 传输到 Python。这包括许多以某种形式相互关联的对象。当我在 Python 代码中收到它们时,使用 protobuf 提供的类型非常丑陋。我的 VIM IDE 在尝试对类型使用自动完成时崩溃了,PyCharm 没有完成 anything 而且通常他们不这样做似乎很荒谬' 为不同的类型提供一些清晰的 class
定义。
在 python 中处理 protobuf 消息时有没有办法获得 IDE 支持?我正在查看 20 多种处理复杂消息的方法,如果没有 IDE 支持,我还不如使用记事本进行编码。
我知道 protobuf 正在使用 metaclasses(尽管我不知道他们为什么这样做)。也许有一种方法可以从该数据生成 python class 文件,或者可能有类似于 typescript typing files.
的方法
我是不是误用了 protobuf?我相信我会以一种可以跨语言使用的方式来描述我的领域模型。在 Java 中,我对生成的 classes 很满意,我可以轻松使用它们。我应该改用 swagger.io 之类的东西吗?
截至目前,没有类似的东西可用。您可能希望关注此问题:https://github.com/google/protobuf/issues/2638 以保持最新。
mypy-protobuf generates the type hint files. But as discussed here 这仅适用于 protobuf 3.0 和 python 2.7 之后的版本。
如果您使用的是最近的 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。
我正在尝试将大量结构化数据从 Java 传输到 Python。这包括许多以某种形式相互关联的对象。当我在 Python 代码中收到它们时,使用 protobuf 提供的类型非常丑陋。我的 VIM IDE 在尝试对类型使用自动完成时崩溃了,PyCharm 没有完成 anything 而且通常他们不这样做似乎很荒谬' 为不同的类型提供一些清晰的 class
定义。
在 python 中处理 protobuf 消息时有没有办法获得 IDE 支持?我正在查看 20 多种处理复杂消息的方法,如果没有 IDE 支持,我还不如使用记事本进行编码。
我知道 protobuf 正在使用 metaclasses(尽管我不知道他们为什么这样做)。也许有一种方法可以从该数据生成 python class 文件,或者可能有类似于 typescript typing files.
的方法我是不是误用了 protobuf?我相信我会以一种可以跨语言使用的方式来描述我的领域模型。在 Java 中,我对生成的 classes 很满意,我可以轻松使用它们。我应该改用 swagger.io 之类的东西吗?
截至目前,没有类似的东西可用。您可能希望关注此问题:https://github.com/google/protobuf/issues/2638 以保持最新。
mypy-protobuf generates the type hint files. But as discussed here 这仅适用于 protobuf 3.0 和 python 2.7 之后的版本。
如果您使用的是最近的 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。