aristaproto


Namearistaproto JSON
Version 0.1.2 PyPI version JSON
download
home_pagehttps://github.com/aristanetworks/python-aristaproto
SummaryArista Protobuf / Python gRPC bindings generator & library
upload_time2024-04-30 04:42:17
maintainerNone
docs_urlNone
authorArista Networks
requires_python<4.0,>=3.9
licenseMIT
keywords protobuf grpc aristanetworks arista
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Arista Protobuf / Python gRPC bindings generator & library

This was originally forked from <https://github.com/danielgtaylor/python-betterproto> @ [b8a091ae7055dd949d193695a06c9536ad51eea8](https://github.com/danielgtaylor/python-betterproto/commit/b8a091ae7055dd949d193695a06c9536ad51eea8).

Afterwards commits up to `1f88b67eeb9871d33da154fd2c859b9d1aed62c1` on `python-betterproto` have been cherry-picked.

Changes in this project compared with the base project:

- Renamed to `aristaproto`.
- Cut support for Python < 3.9.
- Updating various CI actions and dependencies.
- Merged docs from multiple `rst` files to MarkDown.
- Keep nanosecond precision for `Timestamp`.
  - Subclass `datetime` to store the original nano-second value when converting from `Timestamp` to `datetime`.
  - On conversion from the subclass of `datetime` to `Timestamp` the original nano-second value is restored.

## Installation

First, install the package. Note that the `[compiler]` feature flag tells it to install extra dependencies only needed by the `protoc` plugin:

```sh
# Install both the library and compiler
pip install "aristaproto[compiler]"

# Install just the library (to use the generated code output)
pip install aristaproto
```

## Getting Started

### Compiling proto files

Given you installed the compiler and have a proto file, e.g `example.proto`:

```protobuf
syntax = "proto3";

package hello;

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

You can run the following to invoke protoc directly:

```sh
mkdir lib
protoc -I . --python_aristaproto_out=lib example.proto
```

or run the following to invoke protoc via grpcio-tools:

```sh
pip install grpcio-tools
python -m grpc_tools.protoc -I . --python_aristaproto_out=lib example.proto
```

This will generate `lib/hello/__init__.py` which looks like:

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

import aristaproto


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

    message: str = aristaproto.string_field(1)
```

Now you can use it!

```python
>>> from lib.hello import Greeting
>>> test = Greeting()
>>> test
Greeting(message='')

>>> test.message = "Hey!"
>>> test
Greeting(message="Hey!")

>>> serialized = bytes(test)
>>> serialized
b'\n\x04Hey!'

>>> another = Greeting().parse(serialized)
>>> another
Greeting(message="Hey!")

>>> another.to_dict()
{"message": "Hey!"}
>>> another.to_json(indent=2)
'{\n  "message": "Hey!"\n}'
```

### Async gRPC Support

The generated Protobuf `Message` classes are compatible with [grpclib](https://github.com/vmagamedov/grpclib) so you are free to use it if you like. That said, this project also includes support for async gRPC stub generation with better static type checking and code completion support. It is enabled by default.

Given an example service definition:

```protobuf
syntax = "proto3";

package echo;

message EchoRequest {
  string value = 1;
  // Number of extra times to echo
  uint32 extra_times = 2;
}

message EchoResponse {
  repeated string values = 1;
}

message EchoStreamResponse  {
  string value = 1;
}

service Echo {
  rpc Echo(EchoRequest) returns (EchoResponse);
  rpc EchoStream(EchoRequest) returns (stream EchoStreamResponse);
}
```

Generate echo proto file:

```sh
python -m grpc_tools.protoc -I . --python_aristaproto_out=. echo.proto
```

A client can be implemented as follows:

```python
import asyncio
import echo

from grpclib.client import Channel


async def main():
    channel = Channel(host="127.0.0.1", port=50051)
    service = echo.EchoStub(channel)
    response = await service.echo(echo.EchoRequest(value="hello", extra_times=1))
    print(response)

    async for response in service.echo_stream(echo.EchoRequest(value="hello", extra_times=1)):
        print(response)

    # don't forget to close the channel when done!
    channel.close()


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

```

which would output

```python
EchoResponse(values=['hello', 'hello'])
EchoStreamResponse(value='hello')
EchoStreamResponse(value='hello')
```

This project also produces server-facing stubs that can be used to implement a Python
gRPC server.
To use them, simply subclass the base class in the generated files and override the
service methods:

```python
import asyncio
from echo import EchoBase, EchoRequest, EchoResponse, EchoStreamResponse
from grpclib.server import Server
from typing import AsyncIterator


class EchoService(EchoBase):
    async def echo(self, echo_request: "EchoRequest") -> "EchoResponse":
        return EchoResponse([echo_request.value for _ in range(echo_request.extra_times)])

    async def echo_stream(self, echo_request: "EchoRequest") -> AsyncIterator["EchoStreamResponse"]:
        for _ in range(echo_request.extra_times):
            yield EchoStreamResponse(echo_request.value)


async def main():
    server = Server([EchoService()])
    await server.start("127.0.0.1", 50051)
    await server.wait_closed()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
```

### JSON

Both serializing and parsing are supported to/from JSON and Python dictionaries using the following methods:

- Dicts: `Message().to_dict()`, `Message().from_dict(...)`
- JSON: `Message().to_json()`, `Message().from_json(...)`

For compatibility the default is to convert field names to `camelCase`. You can control this behavior by passing a casing value, e.g:

```python
MyMessage().to_dict(casing=aristaproto.Casing.SNAKE)
```

### Determining if a message was sent

Sometimes it is useful to be able to determine whether a message has been sent on the wire. This is how the Google wrapper types work to let you know whether a value is unset, set as the default (zero value), or set as something else, for example.

Use `aristaproto.serialized_on_wire(message)` to determine if it was sent. This is a little bit different from the official Google generated Python code, and it lives outside the generated `Message` class to prevent name clashes. Note that it **only** supports Proto 3 and thus can **only** be used to check if `Message` fields are set. You cannot check if a scalar was sent on the wire.

```py
# Old way (official Google Protobuf package)
>>> mymessage.HasField('myfield')

# New way (this project)
>>> aristaproto.serialized_on_wire(mymessage.myfield)
```

### One-of Support

Protobuf supports grouping fields in a `oneof` clause. Only one of the fields in the group may be set at a given time. For example, given the proto:

```protobuf
syntax = "proto3";

message Test {
  oneof foo {
    bool on = 1;
    int32 count = 2;
    string name = 3;
  }
}
```

On Python 3.10 and later, you can use a `match` statement to access the provided one-of field, which supports type-checking:

```py
test = Test()
match test:
    case Test(on=value):
        print(value)  # value: bool
    case Test(count=value):
        print(value)  # value: int
    case Test(name=value):
        print(value)  # value: str
    case _:
        print("No value provided")
```

You can also use `aristaproto.which_one_of(message, group_name)` to determine which of the fields was set. It returns a tuple of the field name and value, or a blank string and `None` if unset.

```py
>>> test = Test()
>>> aristaproto.which_one_of(test, "foo")
["", None]

>>> test.on = True
>>> aristaproto.which_one_of(test, "foo")
["on", True]

# Setting one member of the group resets the others.
>>> test.count = 57
>>> aristaproto.which_one_of(test, "foo")
["count", 57]

# Default (zero) values also work.
>>> test.name = ""
>>> aristaproto.which_one_of(test, "foo")
["name", ""]
```

Again this is a little different than the official Google code generator:

```py
# Old way (official Google protobuf package)
>>> message.WhichOneof("group")
"foo"

# New way (this project)
>>> aristaproto.which_one_of(message, "group")
["foo", "foo's value"]
```

### Well-Known Google Types

Google provides several well-known message types like a timestamp, duration, and several wrappers used to provide optional zero value support. Each of these has a special JSON representation and is handled a little differently from normal messages. The Python mapping for these is as follows:

| Google Message              | Python Type                              | Default                |
| --------------------------- | ---------------------------------------- | ---------------------- |
| `google.protobuf.duration`  | [`datetime.timedelta`][td]               | `0`                    |
| `google.protobuf.timestamp` | Timezone-aware [`datetime.datetime`][dt] | `1970-01-01T00:00:00Z` |
| `google.protobuf.*Value`    | `Optional[...]`                          | `None`                 |
| `google.protobuf.*`         | `aristaproto.lib.google.protobuf.*`      | `None`                 |

[td]: https://docs.python.org/3/library/datetime.html#timedelta-objects
[dt]: https://docs.python.org/3/library/datetime.html#datetime.datetime

For the wrapper types, the Python type corresponds to the wrapped type, e.g. `google.protobuf.BoolValue` becomes `Optional[bool]` while `google.protobuf.Int32Value` becomes `Optional[int]`. All of the optional values default to `None`, so don't forget to check for that possible state. Given:

```protobuf
syntax = "proto3";

import "google/protobuf/duration.proto";
import "google/protobuf/timestamp.proto";
import "google/protobuf/wrappers.proto";

message Test {
  google.protobuf.BoolValue maybe = 1;
  google.protobuf.Timestamp ts = 2;
  google.protobuf.Duration duration = 3;
}
```

You can do stuff like:

```py
>>> t = Test().from_dict({"maybe": True, "ts": "2019-01-01T12:00:00Z", "duration": "1.200s"})
>>> t
Test(maybe=True, ts=datetime.datetime(2019, 1, 1, 12, 0, tzinfo=datetime.timezone.utc), duration=datetime.timedelta(seconds=1, microseconds=200000))

>>> t.ts - t.duration
datetime.datetime(2019, 1, 1, 11, 59, 58, 800000, tzinfo=datetime.timezone.utc)

>>> t.ts.isoformat()
'2019-01-01T12:00:00+00:00'

>>> t.maybe = None
>>> t.to_dict()
{'ts': '2019-01-01T12:00:00Z', 'duration': '1.200s'}
```

## Generating Pydantic Models

You can use python-aristaproto to generate pydantic based models, using
pydantic dataclasses. This means the results of the protobuf unmarshalling will
be typed checked. The usage is the same, but you need to add a custom option
when calling the protobuf compiler:

```sh
protoc -I . --python_aristaproto_opt=pydantic_dataclasses --python_aristaproto_out=lib example.proto
```

With the important change being `--python_aristaproto_opt=pydantic_dataclasses`. This will
swap the dataclass implementation from the builtin python dataclass to the
pydantic dataclass. You must have pydantic as a dependency in your project for
this to work.

## Development

### Requirements

- Python (3.9 or higher)

- [poetry](https://python-poetry.org/docs/#installation)
  *Needed to install dependencies in a virtual environment*

- [poethepoet](https://github.com/nat-n/poethepoet) for running development tasks as defined in pyproject.toml
  - Can be installed to your host environment via `pip install poethepoet` then executed as simple `poe`
  - or run from the poetry venv as `poetry run poe`

### Setup

```sh
# Get set up with the virtual env & dependencies
poetry install -E compiler

# Activate the poetry environment
poetry shell
```

### Code style

This project enforces [black](https://github.com/psf/black) python code formatting.

Before committing changes run:

```sh
poe format
```

To avoid merge conflicts later, non-black formatted python code will fail in CI.

### Tests

There are two types of tests:

1. Standard tests
2. Custom tests

#### Standard tests

Adding a standard test case is easy.

- Create a new directory `aristaproto/tests/inputs/<name>`
  - add `<name>.proto`  with a message called `Test`
  - add `<name>.json` with some test data (optional)

It will be picked up automatically when you run the tests.

- See also: [Standard Tests Development Guide](tests/README.md)

#### Custom tests

Custom tests are found in `tests/test_*.py` and are run with pytest.

#### Running

Here's how to run the tests.

```sh
# Generate assets from sample .proto files required by the tests
poe generate
# Run the tests
poe test
```

To run tests as they are run in CI (with tox) run:

```sh
poe full-test
```

### (Re)compiling Google Well-known Types

Betterproto includes compiled versions for Google's well-known types at [src/aristaproto/lib/google](src/aristaproto/lib/google).
Be sure to regenerate these files when modifying the plugin output format, and validate by running the tests.

Normally, the plugin does not compile any references to `google.protobuf`, since they are pre-compiled. To force compilation of `google.protobuf`, use the option `--custom_opt=INCLUDE_GOOGLE`.

Assuming your `google.protobuf` source files (included with all releases of `protoc`) are located in `/usr/local/include`, you can regenerate them as follows:

```sh
protoc \
    --plugin=protoc-gen-custom=src/aristaproto/plugin/main.py \
    --custom_opt=INCLUDE_GOOGLE \
    --custom_out=src/aristaproto/lib \
    -I /usr/local/include/ \
    /usr/local/include/google/protobuf/*.proto
```

## License

Copyright 2023 Arista Networks

Copyright 2019-2023 Daniel G. Taylor

This software is free to use under the MIT license. See the [LICENSE](./LICENSE.md) file for license text.


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/aristanetworks/python-aristaproto",
    "name": "aristaproto",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.9",
    "maintainer_email": null,
    "keywords": "protobuf, gRPC, aristanetworks, arista",
    "author": "Arista Networks",
    "author_email": "ansible@arista.com",
    "download_url": null,
    "platform": null,
    "description": "# Arista Protobuf / Python gRPC bindings generator & library\n\nThis was originally forked from <https://github.com/danielgtaylor/python-betterproto> @ [b8a091ae7055dd949d193695a06c9536ad51eea8](https://github.com/danielgtaylor/python-betterproto/commit/b8a091ae7055dd949d193695a06c9536ad51eea8).\n\nAfterwards commits up to `1f88b67eeb9871d33da154fd2c859b9d1aed62c1` on `python-betterproto` have been cherry-picked.\n\nChanges in this project compared with the base project:\n\n- Renamed to `aristaproto`.\n- Cut support for Python < 3.9.\n- Updating various CI actions and dependencies.\n- Merged docs from multiple `rst` files to MarkDown.\n- Keep nanosecond precision for `Timestamp`.\n  - Subclass `datetime` to store the original nano-second value when converting from `Timestamp` to `datetime`.\n  - On conversion from the subclass of `datetime` to `Timestamp` the original nano-second value is restored.\n\n## Installation\n\nFirst, install the package. Note that the `[compiler]` feature flag tells it to install extra dependencies only needed by the `protoc` plugin:\n\n```sh\n# Install both the library and compiler\npip install \"aristaproto[compiler]\"\n\n# Install just the library (to use the generated code output)\npip install aristaproto\n```\n\n## Getting Started\n\n### Compiling proto files\n\nGiven you installed the compiler and have a proto file, e.g `example.proto`:\n\n```protobuf\nsyntax = \"proto3\";\n\npackage hello;\n\n// Greeting represents a message you can tell a user.\nmessage Greeting {\n  string message = 1;\n}\n```\n\nYou can run the following to invoke protoc directly:\n\n```sh\nmkdir lib\nprotoc -I . --python_aristaproto_out=lib example.proto\n```\n\nor run the following to invoke protoc via grpcio-tools:\n\n```sh\npip install grpcio-tools\npython -m grpc_tools.protoc -I . --python_aristaproto_out=lib example.proto\n```\n\nThis will generate `lib/hello/__init__.py` which looks like:\n\n```python\n# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# sources: example.proto\n# plugin: python-aristaproto\nfrom dataclasses import dataclass\n\nimport aristaproto\n\n\n@dataclass\nclass Greeting(aristaproto.Message):\n    \"\"\"Greeting represents a message you can tell a user.\"\"\"\n\n    message: str = aristaproto.string_field(1)\n```\n\nNow you can use it!\n\n```python\n>>> from lib.hello import Greeting\n>>> test = Greeting()\n>>> test\nGreeting(message='')\n\n>>> test.message = \"Hey!\"\n>>> test\nGreeting(message=\"Hey!\")\n\n>>> serialized = bytes(test)\n>>> serialized\nb'\\n\\x04Hey!'\n\n>>> another = Greeting().parse(serialized)\n>>> another\nGreeting(message=\"Hey!\")\n\n>>> another.to_dict()\n{\"message\": \"Hey!\"}\n>>> another.to_json(indent=2)\n'{\\n  \"message\": \"Hey!\"\\n}'\n```\n\n### Async gRPC Support\n\nThe generated Protobuf `Message` classes are compatible with [grpclib](https://github.com/vmagamedov/grpclib) so you are free to use it if you like. That said, this project also includes support for async gRPC stub generation with better static type checking and code completion support. It is enabled by default.\n\nGiven an example service definition:\n\n```protobuf\nsyntax = \"proto3\";\n\npackage echo;\n\nmessage EchoRequest {\n  string value = 1;\n  // Number of extra times to echo\n  uint32 extra_times = 2;\n}\n\nmessage EchoResponse {\n  repeated string values = 1;\n}\n\nmessage EchoStreamResponse  {\n  string value = 1;\n}\n\nservice Echo {\n  rpc Echo(EchoRequest) returns (EchoResponse);\n  rpc EchoStream(EchoRequest) returns (stream EchoStreamResponse);\n}\n```\n\nGenerate echo proto file:\n\n```sh\npython -m grpc_tools.protoc -I . --python_aristaproto_out=. echo.proto\n```\n\nA client can be implemented as follows:\n\n```python\nimport asyncio\nimport echo\n\nfrom grpclib.client import Channel\n\n\nasync def main():\n    channel = Channel(host=\"127.0.0.1\", port=50051)\n    service = echo.EchoStub(channel)\n    response = await service.echo(echo.EchoRequest(value=\"hello\", extra_times=1))\n    print(response)\n\n    async for response in service.echo_stream(echo.EchoRequest(value=\"hello\", extra_times=1)):\n        print(response)\n\n    # don't forget to close the channel when done!\n    channel.close()\n\n\nif __name__ == \"__main__\":\n    loop = asyncio.get_event_loop()\n    loop.run_until_complete(main())\n\n```\n\nwhich would output\n\n```python\nEchoResponse(values=['hello', 'hello'])\nEchoStreamResponse(value='hello')\nEchoStreamResponse(value='hello')\n```\n\nThis project also produces server-facing stubs that can be used to implement a Python\ngRPC server.\nTo use them, simply subclass the base class in the generated files and override the\nservice methods:\n\n```python\nimport asyncio\nfrom echo import EchoBase, EchoRequest, EchoResponse, EchoStreamResponse\nfrom grpclib.server import Server\nfrom typing import AsyncIterator\n\n\nclass EchoService(EchoBase):\n    async def echo(self, echo_request: \"EchoRequest\") -> \"EchoResponse\":\n        return EchoResponse([echo_request.value for _ in range(echo_request.extra_times)])\n\n    async def echo_stream(self, echo_request: \"EchoRequest\") -> AsyncIterator[\"EchoStreamResponse\"]:\n        for _ in range(echo_request.extra_times):\n            yield EchoStreamResponse(echo_request.value)\n\n\nasync def main():\n    server = Server([EchoService()])\n    await server.start(\"127.0.0.1\", 50051)\n    await server.wait_closed()\n\nif __name__ == '__main__':\n    loop = asyncio.get_event_loop()\n    loop.run_until_complete(main())\n```\n\n### JSON\n\nBoth serializing and parsing are supported to/from JSON and Python dictionaries using the following methods:\n\n- Dicts: `Message().to_dict()`, `Message().from_dict(...)`\n- JSON: `Message().to_json()`, `Message().from_json(...)`\n\nFor compatibility the default is to convert field names to `camelCase`. You can control this behavior by passing a casing value, e.g:\n\n```python\nMyMessage().to_dict(casing=aristaproto.Casing.SNAKE)\n```\n\n### Determining if a message was sent\n\nSometimes it is useful to be able to determine whether a message has been sent on the wire. This is how the Google wrapper types work to let you know whether a value is unset, set as the default (zero value), or set as something else, for example.\n\nUse `aristaproto.serialized_on_wire(message)` to determine if it was sent. This is a little bit different from the official Google generated Python code, and it lives outside the generated `Message` class to prevent name clashes. Note that it **only** supports Proto 3 and thus can **only** be used to check if `Message` fields are set. You cannot check if a scalar was sent on the wire.\n\n```py\n# Old way (official Google Protobuf package)\n>>> mymessage.HasField('myfield')\n\n# New way (this project)\n>>> aristaproto.serialized_on_wire(mymessage.myfield)\n```\n\n### One-of Support\n\nProtobuf supports grouping fields in a `oneof` clause. Only one of the fields in the group may be set at a given time. For example, given the proto:\n\n```protobuf\nsyntax = \"proto3\";\n\nmessage Test {\n  oneof foo {\n    bool on = 1;\n    int32 count = 2;\n    string name = 3;\n  }\n}\n```\n\nOn Python 3.10 and later, you can use a `match` statement to access the provided one-of field, which supports type-checking:\n\n```py\ntest = Test()\nmatch test:\n    case Test(on=value):\n        print(value)  # value: bool\n    case Test(count=value):\n        print(value)  # value: int\n    case Test(name=value):\n        print(value)  # value: str\n    case _:\n        print(\"No value provided\")\n```\n\nYou can also use `aristaproto.which_one_of(message, group_name)` to determine which of the fields was set. It returns a tuple of the field name and value, or a blank string and `None` if unset.\n\n```py\n>>> test = Test()\n>>> aristaproto.which_one_of(test, \"foo\")\n[\"\", None]\n\n>>> test.on = True\n>>> aristaproto.which_one_of(test, \"foo\")\n[\"on\", True]\n\n# Setting one member of the group resets the others.\n>>> test.count = 57\n>>> aristaproto.which_one_of(test, \"foo\")\n[\"count\", 57]\n\n# Default (zero) values also work.\n>>> test.name = \"\"\n>>> aristaproto.which_one_of(test, \"foo\")\n[\"name\", \"\"]\n```\n\nAgain this is a little different than the official Google code generator:\n\n```py\n# Old way (official Google protobuf package)\n>>> message.WhichOneof(\"group\")\n\"foo\"\n\n# New way (this project)\n>>> aristaproto.which_one_of(message, \"group\")\n[\"foo\", \"foo's value\"]\n```\n\n### Well-Known Google Types\n\nGoogle provides several well-known message types like a timestamp, duration, and several wrappers used to provide optional zero value support. Each of these has a special JSON representation and is handled a little differently from normal messages. The Python mapping for these is as follows:\n\n| Google Message              | Python Type                              | Default                |\n| --------------------------- | ---------------------------------------- | ---------------------- |\n| `google.protobuf.duration`  | [`datetime.timedelta`][td]               | `0`                    |\n| `google.protobuf.timestamp` | Timezone-aware [`datetime.datetime`][dt] | `1970-01-01T00:00:00Z` |\n| `google.protobuf.*Value`    | `Optional[...]`                          | `None`                 |\n| `google.protobuf.*`         | `aristaproto.lib.google.protobuf.*`      | `None`                 |\n\n[td]: https://docs.python.org/3/library/datetime.html#timedelta-objects\n[dt]: https://docs.python.org/3/library/datetime.html#datetime.datetime\n\nFor the wrapper types, the Python type corresponds to the wrapped type, e.g. `google.protobuf.BoolValue` becomes `Optional[bool]` while `google.protobuf.Int32Value` becomes `Optional[int]`. All of the optional values default to `None`, so don't forget to check for that possible state. Given:\n\n```protobuf\nsyntax = \"proto3\";\n\nimport \"google/protobuf/duration.proto\";\nimport \"google/protobuf/timestamp.proto\";\nimport \"google/protobuf/wrappers.proto\";\n\nmessage Test {\n  google.protobuf.BoolValue maybe = 1;\n  google.protobuf.Timestamp ts = 2;\n  google.protobuf.Duration duration = 3;\n}\n```\n\nYou can do stuff like:\n\n```py\n>>> t = Test().from_dict({\"maybe\": True, \"ts\": \"2019-01-01T12:00:00Z\", \"duration\": \"1.200s\"})\n>>> t\nTest(maybe=True, ts=datetime.datetime(2019, 1, 1, 12, 0, tzinfo=datetime.timezone.utc), duration=datetime.timedelta(seconds=1, microseconds=200000))\n\n>>> t.ts - t.duration\ndatetime.datetime(2019, 1, 1, 11, 59, 58, 800000, tzinfo=datetime.timezone.utc)\n\n>>> t.ts.isoformat()\n'2019-01-01T12:00:00+00:00'\n\n>>> t.maybe = None\n>>> t.to_dict()\n{'ts': '2019-01-01T12:00:00Z', 'duration': '1.200s'}\n```\n\n## Generating Pydantic Models\n\nYou can use python-aristaproto to generate pydantic based models, using\npydantic dataclasses. This means the results of the protobuf unmarshalling will\nbe typed checked. The usage is the same, but you need to add a custom option\nwhen calling the protobuf compiler:\n\n```sh\nprotoc -I . --python_aristaproto_opt=pydantic_dataclasses --python_aristaproto_out=lib example.proto\n```\n\nWith the important change being `--python_aristaproto_opt=pydantic_dataclasses`. This will\nswap the dataclass implementation from the builtin python dataclass to the\npydantic dataclass. You must have pydantic as a dependency in your project for\nthis to work.\n\n## Development\n\n### Requirements\n\n- Python (3.9 or higher)\n\n- [poetry](https://python-poetry.org/docs/#installation)\n  *Needed to install dependencies in a virtual environment*\n\n- [poethepoet](https://github.com/nat-n/poethepoet) for running development tasks as defined in pyproject.toml\n  - Can be installed to your host environment via `pip install poethepoet` then executed as simple `poe`\n  - or run from the poetry venv as `poetry run poe`\n\n### Setup\n\n```sh\n# Get set up with the virtual env & dependencies\npoetry install -E compiler\n\n# Activate the poetry environment\npoetry shell\n```\n\n### Code style\n\nThis project enforces [black](https://github.com/psf/black) python code formatting.\n\nBefore committing changes run:\n\n```sh\npoe format\n```\n\nTo avoid merge conflicts later, non-black formatted python code will fail in CI.\n\n### Tests\n\nThere are two types of tests:\n\n1. Standard tests\n2. Custom tests\n\n#### Standard tests\n\nAdding a standard test case is easy.\n\n- Create a new directory `aristaproto/tests/inputs/<name>`\n  - add `<name>.proto`  with a message called `Test`\n  - add `<name>.json` with some test data (optional)\n\nIt will be picked up automatically when you run the tests.\n\n- See also: [Standard Tests Development Guide](tests/README.md)\n\n#### Custom tests\n\nCustom tests are found in `tests/test_*.py` and are run with pytest.\n\n#### Running\n\nHere's how to run the tests.\n\n```sh\n# Generate assets from sample .proto files required by the tests\npoe generate\n# Run the tests\npoe test\n```\n\nTo run tests as they are run in CI (with tox) run:\n\n```sh\npoe full-test\n```\n\n### (Re)compiling Google Well-known Types\n\nBetterproto includes compiled versions for Google's well-known types at [src/aristaproto/lib/google](src/aristaproto/lib/google).\nBe sure to regenerate these files when modifying the plugin output format, and validate by running the tests.\n\nNormally, the plugin does not compile any references to `google.protobuf`, since they are pre-compiled. To force compilation of `google.protobuf`, use the option `--custom_opt=INCLUDE_GOOGLE`.\n\nAssuming your `google.protobuf` source files (included with all releases of `protoc`) are located in `/usr/local/include`, you can regenerate them as follows:\n\n```sh\nprotoc \\\n    --plugin=protoc-gen-custom=src/aristaproto/plugin/main.py \\\n    --custom_opt=INCLUDE_GOOGLE \\\n    --custom_out=src/aristaproto/lib \\\n    -I /usr/local/include/ \\\n    /usr/local/include/google/protobuf/*.proto\n```\n\n## License\n\nCopyright 2023 Arista Networks\n\nCopyright 2019-2023 Daniel G. Taylor\n\nThis software is free to use under the MIT license. See the [LICENSE](./LICENSE.md) file for license text.\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Arista Protobuf / Python gRPC bindings generator & library",
    "version": "0.1.2",
    "project_urls": {
        "Homepage": "https://github.com/aristanetworks/python-aristaproto",
        "Repository": "https://github.com/aristanetworks/python-aristaproto"
    },
    "split_keywords": [
        "protobuf",
        " grpc",
        " aristanetworks",
        " arista"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b05bb6dfc880f3dcafb46003ad027f873bf4a2302bb0c85bc91583072124856c",
                "md5": "c6e93141be99283dbfebf3df7abfb91b",
                "sha256": "7c28055bbc25930a0b2cf2ffd987374e54cd6482b4e086d3e24be45cf665f1d3"
            },
            "downloads": -1,
            "filename": "aristaproto-0.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c6e93141be99283dbfebf3df7abfb91b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.9",
            "size": 100493,
            "upload_time": "2024-04-30T04:42:17",
            "upload_time_iso_8601": "2024-04-30T04:42:17.735594Z",
            "url": "https://files.pythonhosted.org/packages/b0/5b/b6dfc880f3dcafb46003ad027f873bf4a2302bb0c85bc91583072124856c/aristaproto-0.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-30 04:42:17",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aristanetworks",
    "github_project": "python-aristaproto",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aristaproto"
}
        
Elapsed time: 0.33763s