# pydantic-protobuf-gen **Repository Path**: geebytes/pydantic-protobuf-gen ## Basic Information - **Project Name**: pydantic-protobuf-gen - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-01-17 - **Last Updated**: 2025-01-17 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # protobuf-pydantic-gen pydantic model 和 protobuf message 互相转换工具,实现`.proto`文件生成pydantic `BaseModel`类。 ## 特性 - 支持protobuf基本类型转换为python基本类型 - 支持protobuf描述语言转换为pydantic `BaseModel`类 - 支持protobuf描述语言转换为`sqlmodel` ORM模型 - 为`BaseModel`类实现`to_protobuf` 和 `from_protobuf`方法,实现pydantic model 和 protobuf message 互相转换 - 为protobuf 描述文件提供`pydantic BaseModel Field` 字段的参数选项 ## 安装 ```shell pip install protobuf-pydantic-gen ``` ## 示例 ```protobuf syntax = "proto3"; import "google/protobuf/descriptor.proto"; import "protobuf_pydantic_gen/pydantic.proto"; import "google/protobuf/timestamp.proto"; import "google/protobuf/any.proto"; import "constant.proto"; import "example2.proto"; package pydantic_example; message Nested { string name = 1[(pydantic.field) = {description: "Name of the example",example: "'ohn Doe",alias: "full_name",default: "John Doe",max_length:128,primary_key:true}]; } message Example { option (pydantic.database) = { as_table: true table_name: "users", compound_index:{ indexs:["name","age"], index_type:"UNIQUE", name:"uni_name_age" }, compound_index:{ indexs:["name"], index_type:"PRIMARY", name:"index_name" } }; string name = 1[(pydantic.field) = {description: "Name of the example",alias: "full_name",default: "John Doe",max_length:128,primary_key:true}]; optional int32 age = 2 [(pydantic.field) = {description: "Age of the example",alias: "years",default: "30"}]; repeated string emails = 3 [(pydantic.field) = {description: "Emails of the example",default:"[]"}]; repeated Example2 examples = 9 [(pydantic.field) = {description: "Nested message",sa_column_type:"JSON"}]; map entry = 4 [(pydantic.field) = {description: "Properties of the example",default:"{}"}]; Nested nested=8[(pydantic.field) = {description: "Nested message",sa_column_type:"JSON"}]; google.protobuf.Timestamp created_at = 5 [(pydantic.field) = {description: "Creation date of the example",default: "datetime.datetime.now()",required: true}]; ExampleType type = 6 [(pydantic.field) = {description: "Type of the example",default: "ExampleType.TYPE1",sa_column_type:"Enum[ExampleType]"}]; float score = 7 [(pydantic.field) = {description: "Score of the example",default: "0.0",gt: 0.0,le: 100.0,field_type: "Integer"}]; } ``` ## 使用 ```shell python3 -m grpc_tools.protoc --proto_path=./protos -I=./protos -I=./ --python_out=./pb --pyi_out=./pb --grpc_python_out=./pb --pydantic_out=./models "./protos/example.proto" ```