How to generate python class files from protobuf

pas*_*oop 9 python protocol-buffers grpc

I am trying to transfer large amounts of structured data from Java to Python. That includes many objects that are related to each other in some form or another. When I receive them in my Python code, it's quiet ugly to work with the types that are provided by protobuf. My VIM IDE crashed when trying to use autocomplete on the types, PyCharm doesn't complete anything and generally it just seems absurd that they don't provide some clean class definition for the different types.

Is there a way to get IDE support while working with protobuf messages in python? I'm looking at 20+ methods handling complex messages and without IDE support I might as well code with notepad.

在此处输入图片说明

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

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

Dan*_*iel 13

如果您使用的是最近的 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;
}
Run Code Online (Sandbox Code Playgroud)

将生成以下输出:

# 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)
Run Code Online (Sandbox Code Playgroud)

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


tuk*_*tuk 2

mypy-protobuf生成类型提示文件。但正如这里所讨论的,这只适用于 protobuf 3.0 和 python 2.7 及以上版本。