yc-protobuf3-to-dict


Nameyc-protobuf3-to-dict JSON
Version 0.3.0 PyPI version JSON
download
home_pagehttps://github.com/yepcord/protobuf-to-dict
SummaryA tiny Python library for creating Python dicts from protocol buffers and the reverse.
upload_time2023-11-22 09:27:52
maintainer
docs_urlNone
authorKapor Zhu
requires_python>=3.9,<4.0
licensePublic Domain
keywords protobuf json dict
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # protobuf-to-dict

protobuf-to-dict is a small Python library for creating dicts from protocol
buffers. It is intended to be used as an intermediate step before
serialization (e.g. to JSON).

# Installation

Note: This is a fork. Install by pointing to this github repo.

For example:

`pip install git@github.com:yepcord/protobuf-to-dict.git`

# Example

Given the `google.protobuf.message.Message` subclass `MyMessage`:

```python
>> > from protobuf3_to_dict import protobuf_to_dict, dict_to_protobuf
>> > my_message = MyMessage()
>> >  # pb_my_message is a protobuf string
>> > my_message.ParseFromString(pb_my_message)
>> > my_message_dict = protobuf_to_dict(my_message)
>> > print(my_message_dict)
{'message': 'Hello'}
>> > msg = dict_to_protobuf(MyMessage, values=my_message_dict)
>> > assert msg == my_message
True
```

# Datetime conversion

This package automatically converts Python's datetime objects to Google's Timestamp and vice-versa.
If you want to manually do the conversion, the functions are:

```py
from protobuf3_to_dict import datetime_to_timestamp, timestamp_to_datetime

timestamp = datetime_to_timestamp(sample_datetime)
result_sample_datetime = timestamp_to_datetime(timestamp)
assert sample_datetime == result_sample_datetime
```

# Getting all fields, field names and options of a protobuf class

For example in the tests folder you can find sample.proto:

```
message Obj {
    int32 id = 1 [(is_optional) = true];
    string item_id = 2;
    google.protobuf.Timestamp transacted_at = 3;
    Status status = 5;
}
```

Then you can:

```py
>> > from protobuf3_to_dict import get_field_names_and_options
>> > for field, field_name, options in get_field_names_and_options(sample_pb2.Obj):
    ...
print('name: {}, options: {}'.format(field_name, options))

name: id, options: {'is_optional': True}
name: item_id, options: {}
name: transacted_at, options: {}
name: status, options: {}
```

# Validation for required fields

Protobuf 3 does not have a notion of required vs. optional fields. Everything is optional. However if you need some sort of validation before converting your dictionary to a protobuf object, first of all you need to add an option to your protobuf messages that is called `is_optional`. Note that this is different than the `optional` keyword in Prorobuf 2. This is an "option":

For example in the tests folder you can find sample.proto:

```
message Obj {
    int32 id = 1 [(is_optional) = true];
    string item_id = 2;
    google.protobuf.Timestamp transacted_at = 3;
    Status status = 5;
}
```

Then you can validate if a dictionary has all the fields you need:

```py
>> > import datetime
>> > from protobuf3_to_dict import validate_dict_for_required_pb_fields
>> >
>> > dic = {'item_id': 2, 'transacted_at': datetime.datetime.now(), 'status': 0}
>> > from tests import sample_pb2
>> > validate_dict_for_required_pb_fields(pb=sample_pb2.Obj, dic=dic)
```

But if you have missing fields:

```py
>>> dic = {'item_id': 2}
>>> validate_dict_for_required_pb_fields(pb=sample_pb2.Obj, dic=dic)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "protobuf-to-dict/protobuf_to_dict/convertor.py", line 274, in validate_dict_for_required_pb_fields
    raise FieldsMissing('Missing fields: {}'.format(', '.join(missing_fields)))
protobuf_to_dict.convertor.FieldsMissing: Missing fields: transacted_at, status
````

## Caveats

This library grew out of the desire to serialize a protobuf-encoded message to
[JSON](http://json.org/). As JSON has no built-in binary type (all strings in
JSON are Unicode strings), any field whose type is
`FieldDescriptor.TYPE_BYTES` is, by default, converted to a base64-encoded
string.

If you want to override this behaviour, you may do so by passing
`protobuf_to_dict` a dictionary of protobuf types to callables via the
`type_callable_map` kwarg:

```python
>> > from copy import copy
>> > from google.protobuf.descriptor import FieldDescriptor
>> > from protobuf3_to_dict import protobuf_to_dict, TYPE_CALLABLE_MAP
>> >
>> > type_callable_map = copy(TYPE_CALLABLE_MAP)
>> >  # convert TYPE_BYTES to a Python bytestring
>> > type_callable_map[FieldDescriptor.TYPE_BYTES] = str
>> >
>> >  # my_message is a google.protobuf.message.Message instance
>> > protobuf_to_dict(my_message, type_callable_map=type_callable_map)
```

By default, the integer representation is used for enum values. To use their
string labels instead, pass `use_enum_labels=True` into `protobuf_to_dict`:

```python
>>> protobuf_to_dict(my_message, use_enum_labels=True)
```

And if you need the enum labels to be automatically converted to lowercase:

```py
>>> protobuf_to_dict(my_message, use_enum_labels=True, lowercase_enum_lables=True)
```

When you convert from dictionary to protobuf, if you need the enums to work both
in lowercase and uppercase, set the `strict=False`.

# Testing

`pytest tests/`

To regenerate `src/tests/sample_pb2.py`:

run the `compile.sh` file inside the tests folder.

# attention
Prorobuf 3.0.0 has supported json now.
Check https://developers.google.com/protocol-buffers/docs/reference/python/ for more details.


# Authors

protobuf-to-dict is written and maintained by
[Ben Hodgson](http://benhodgson.com/), with significant contributions from
[Nino Walker](https://github.com/ninowalker),
[Jonathan Klaassen](https://github.com/jaklaassen), and
[Tristram Gräbener](http://blog.tristramg.eu/).
[Sep Dehpour](http://zepworks.com)

# (Un)license

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/yepcord/protobuf-to-dict",
    "name": "yc-protobuf3-to-dict",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.9,<4.0",
    "maintainer_email": "",
    "keywords": "protobuf,json,dict",
    "author": "Kapor Zhu",
    "author_email": "kapor.zhu@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/c1/3a/0d654101ffeef08c92958647569308054b701d970b6c6c15e63d720418ae/yc_protobuf3_to_dict-0.3.0.tar.gz",
    "platform": null,
    "description": "# protobuf-to-dict\n\nprotobuf-to-dict is a small Python library for creating dicts from protocol\nbuffers. It is intended to be used as an intermediate step before\nserialization (e.g. to JSON).\n\n# Installation\n\nNote: This is a fork. Install by pointing to this github repo.\n\nFor example:\n\n`pip install git@github.com:yepcord/protobuf-to-dict.git`\n\n# Example\n\nGiven the `google.protobuf.message.Message` subclass `MyMessage`:\n\n```python\n>> > from protobuf3_to_dict import protobuf_to_dict, dict_to_protobuf\n>> > my_message = MyMessage()\n>> >  # pb_my_message is a protobuf string\n>> > my_message.ParseFromString(pb_my_message)\n>> > my_message_dict = protobuf_to_dict(my_message)\n>> > print(my_message_dict)\n{'message': 'Hello'}\n>> > msg = dict_to_protobuf(MyMessage, values=my_message_dict)\n>> > assert msg == my_message\nTrue\n```\n\n# Datetime conversion\n\nThis package automatically converts Python's datetime objects to Google's Timestamp and vice-versa.\nIf you want to manually do the conversion, the functions are:\n\n```py\nfrom protobuf3_to_dict import datetime_to_timestamp, timestamp_to_datetime\n\ntimestamp = datetime_to_timestamp(sample_datetime)\nresult_sample_datetime = timestamp_to_datetime(timestamp)\nassert sample_datetime == result_sample_datetime\n```\n\n# Getting all fields, field names and options of a protobuf class\n\nFor example in the tests folder you can find sample.proto:\n\n```\nmessage Obj {\n    int32 id = 1 [(is_optional) = true];\n    string item_id = 2;\n    google.protobuf.Timestamp transacted_at = 3;\n    Status status = 5;\n}\n```\n\nThen you can:\n\n```py\n>> > from protobuf3_to_dict import get_field_names_and_options\n>> > for field, field_name, options in get_field_names_and_options(sample_pb2.Obj):\n    ...\nprint('name: {}, options: {}'.format(field_name, options))\n\nname: id, options: {'is_optional': True}\nname: item_id, options: {}\nname: transacted_at, options: {}\nname: status, options: {}\n```\n\n# Validation for required fields\n\nProtobuf 3 does not have a notion of required vs. optional fields. Everything is optional. However if you need some sort of validation before converting your dictionary to a protobuf object, first of all you need to add an option to your protobuf messages that is called `is_optional`. Note that this is different than the `optional` keyword in Prorobuf 2. This is an \"option\":\n\nFor example in the tests folder you can find sample.proto:\n\n```\nmessage Obj {\n    int32 id = 1 [(is_optional) = true];\n    string item_id = 2;\n    google.protobuf.Timestamp transacted_at = 3;\n    Status status = 5;\n}\n```\n\nThen you can validate if a dictionary has all the fields you need:\n\n```py\n>> > import datetime\n>> > from protobuf3_to_dict import validate_dict_for_required_pb_fields\n>> >\n>> > dic = {'item_id': 2, 'transacted_at': datetime.datetime.now(), 'status': 0}\n>> > from tests import sample_pb2\n>> > validate_dict_for_required_pb_fields(pb=sample_pb2.Obj, dic=dic)\n```\n\nBut if you have missing fields:\n\n```py\n>>> dic = {'item_id': 2}\n>>> validate_dict_for_required_pb_fields(pb=sample_pb2.Obj, dic=dic)\nTraceback (most recent call last):\n  File \"<stdin>\", line 1, in <module>\n  File \"protobuf-to-dict/protobuf_to_dict/convertor.py\", line 274, in validate_dict_for_required_pb_fields\n    raise FieldsMissing('Missing fields: {}'.format(', '.join(missing_fields)))\nprotobuf_to_dict.convertor.FieldsMissing: Missing fields: transacted_at, status\n````\n\n## Caveats\n\nThis library grew out of the desire to serialize a protobuf-encoded message to\n[JSON](http://json.org/). As JSON has no built-in binary type (all strings in\nJSON are Unicode strings), any field whose type is\n`FieldDescriptor.TYPE_BYTES` is, by default, converted to a base64-encoded\nstring.\n\nIf you want to override this behaviour, you may do so by passing\n`protobuf_to_dict` a dictionary of protobuf types to callables via the\n`type_callable_map` kwarg:\n\n```python\n>> > from copy import copy\n>> > from google.protobuf.descriptor import FieldDescriptor\n>> > from protobuf3_to_dict import protobuf_to_dict, TYPE_CALLABLE_MAP\n>> >\n>> > type_callable_map = copy(TYPE_CALLABLE_MAP)\n>> >  # convert TYPE_BYTES to a Python bytestring\n>> > type_callable_map[FieldDescriptor.TYPE_BYTES] = str\n>> >\n>> >  # my_message is a google.protobuf.message.Message instance\n>> > protobuf_to_dict(my_message, type_callable_map=type_callable_map)\n```\n\nBy default, the integer representation is used for enum values. To use their\nstring labels instead, pass `use_enum_labels=True` into `protobuf_to_dict`:\n\n```python\n>>> protobuf_to_dict(my_message, use_enum_labels=True)\n```\n\nAnd if you need the enum labels to be automatically converted to lowercase:\n\n```py\n>>> protobuf_to_dict(my_message, use_enum_labels=True, lowercase_enum_lables=True)\n```\n\nWhen you convert from dictionary to protobuf, if you need the enums to work both\nin lowercase and uppercase, set the `strict=False`.\n\n# Testing\n\n`pytest tests/`\n\nTo regenerate `src/tests/sample_pb2.py`:\n\nrun the `compile.sh` file inside the tests folder.\n\n# attention\nProrobuf 3.0.0 has supported json now.\nCheck https://developers.google.com/protocol-buffers/docs/reference/python/ for more details.\n\n\n# Authors\n\nprotobuf-to-dict is written and maintained by\n[Ben Hodgson](http://benhodgson.com/), with significant contributions from\n[Nino Walker](https://github.com/ninowalker),\n[Jonathan Klaassen](https://github.com/jaklaassen), and\n[Tristram Gr\u00e4bener](http://blog.tristramg.eu/).\n[Sep Dehpour](http://zepworks.com)\n\n# (Un)license\n\nThis is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute\nthis software, either in source code form or as a compiled binary, for any\npurpose, commercial or non-commercial, and by any means.\n\nIn jurisdictions that recognize copyright laws, the author or authors of this\nsoftware dedicate any and all copyright interest in the software to the public\ndomain. We make this dedication for the benefit of the public at large and to\nthe detriment of our heirs and successors. We intend this dedication to be an\novert act of relinquishment in perpetuity of all present and future rights to\nthis software under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to <http://unlicense.org/>\n",
    "bugtrack_url": null,
    "license": "Public Domain",
    "summary": "A tiny Python library for creating Python dicts from protocol buffers and the reverse.",
    "version": "0.3.0",
    "project_urls": {
        "Homepage": "https://github.com/yepcord/protobuf-to-dict",
        "Repository": "https://github.com/yepcord/protobuf-to-dict"
    },
    "split_keywords": [
        "protobuf",
        "json",
        "dict"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f94c7f66c97a2beb4548a054825fa2653181ebbc99ca937e0d9ed7bd750a7185",
                "md5": "150e2aab354cb8e1e7a2c94daf7097e3",
                "sha256": "629e912a229e26c82955d303fd584fcb2613ea92551355dea73f3db44b4eddc6"
            },
            "downloads": -1,
            "filename": "yc_protobuf3_to_dict-0.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "150e2aab354cb8e1e7a2c94daf7097e3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9,<4.0",
            "size": 8387,
            "upload_time": "2023-11-22T09:27:51",
            "upload_time_iso_8601": "2023-11-22T09:27:51.202572Z",
            "url": "https://files.pythonhosted.org/packages/f9/4c/7f66c97a2beb4548a054825fa2653181ebbc99ca937e0d9ed7bd750a7185/yc_protobuf3_to_dict-0.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c13a0d654101ffeef08c92958647569308054b701d970b6c6c15e63d720418ae",
                "md5": "625af1f6be423d324e0d7da9aa43ed41",
                "sha256": "03b75e182318afac94e33161005186868ea307203db1cc054f62a87a89d1a54c"
            },
            "downloads": -1,
            "filename": "yc_protobuf3_to_dict-0.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "625af1f6be423d324e0d7da9aa43ed41",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9,<4.0",
            "size": 6990,
            "upload_time": "2023-11-22T09:27:52",
            "upload_time_iso_8601": "2023-11-22T09:27:52.547940Z",
            "url": "https://files.pythonhosted.org/packages/c1/3a/0d654101ffeef08c92958647569308054b701d970b6c6c15e63d720418ae/yc_protobuf3_to_dict-0.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-22 09:27:52",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "yepcord",
    "github_project": "protobuf-to-dict",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "yc-protobuf3-to-dict"
}
        
Elapsed time: 0.14036s