Skip to main content

Yet another tool that compiles .proto strings and import the outcome Python modules.

Project description

test version wheel python version python implementation

A tool that

  • takes a str containing protobuf messages definitions
  • returns a types.ModuleType instance

It is useful for Python programs needing to parse protobuf messages without having to host .proto files in their code base.

Installation

pip install proto-topy

Example: address book

Adaptation of the protocolbuffers example:

import requests
import sys
from shutil import which
from proto_topy.entities import ProtoModule
from pathlib import Path

# Retrieve protobuf messages definitions
example_source = requests.get(
    "https://raw.githubusercontent.com/protocolbuffers/protobuf/main/"
    "examples/addressbook.proto").text

example_path = Path(
    "protocolbuffers/protobuf/blob/main/examples/addressbook.proto")

# Compile and import
module = (ProtoModule(file_path=example_path, source=example_source)
          .compiled(Path(which("protoc"))))
sys.modules["addressbook"] = module.py

# Produce a serialized address book
address_book = module.py.AddressBook()
person = address_book.people.add()
person.id = 111
person.name = "A Name"
person.email = "a.name@mail.com"
phone_number = person.phones.add()
phone_number.number = "+1234567"
phone_number.type = module.py.Person.MOBILE
with open("address_book.data", "wb") as o:
    o.write(address_book.SerializeToString())

# Use a serialized address book
address_book = module.py.AddressBook()
with open("address_book.data", "rb") as i:
    address_book.ParseFromString(i.read())
    for person in address_book.people:
        print(person.id, person.name, person.email, phone_number.number)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

proto-topy-0.2.0.tar.gz (14.3 kB view hashes)

Uploaded Source

Built Distribution

proto_topy-0.2.0-py3-none-any.whl (6.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page