transmutate


Nametransmutate JSON
Version 0.2.2 PyPI version JSON
download
home_pageNone
SummaryA versatile library for transforming and serializing data models into multiple formats.
upload_time2024-08-12 15:23:34
maintainerNone
docs_urlNone
authorAli Tavallaie
requires_python<4.0,>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![DOI](https://zenodo.org/badge/837882085.svg)](https://zenodo.org/doi/10.5281/zenodo.13226541)
# Transmutate

 Transmutate is a Python library designed to handle dataclass serialization and deserialization across various formats such as JSON, JSONB, and Protocol Buffers (Proto). The library supports both conversion to these formats and validation of dataclass fields.

 ## Features

 - **JSON Serialization**: Convert dataclasses to and from JSON format.
 - **JSONB Serialization**: Convert dataclasses to and from JSONB format, a compact version of JSON.
 - **Protocol Buffers Serialization**: Generate Proto definitions from dataclasses.
 - **Field Validation**: Custom validation for dataclass fields using `validation_<field>` methods.
 - **Service Definitions**: Define gRPC services with customizable RPC methods.
 - **Proto Generator**: Automatically generate Proto files including service and message definitions.
 - **Easy Integration**: Built on top of Python's dataclasses, allowing seamless integration with existing codebases.

 ## Installation

 You can install Transmutate via Poetry by adding it to your `pyproject.toml` file or by using the following command:

 ```bash
 poetry add transmutate
 ```

 Alternatively, if you're using pip, you can install it with:

 ```bash
 pip install transmutate
 ```

 ## Usage

 Below are some examples demonstrating how to use Transmutate with simple dataclasses.

 ### Defining a Dataclass

 You can define your dataclasses using the `BaseModel` from Transmutate, which provides built-in serialization and validation capabilities.

 ```python
 from dataclasses import dataclass, field
 from typing import List, Optional
 from transmutate.base_model import BaseModel

 class Person(BaseModel):
     name: str
     age: int
     email: Optional[str] = None
     phone_numbers: List[str] = field(default_factory=list)

     def validation_age(self):
         if not (0 <= self.age <= 120):
             raise ValueError("Age must be between 0 and 120.")

     def validation_email(self):
         if self.email and "@" not in self.email:
             raise ValueError("Invalid email address.")
 ```

 ### JSON Serialization

 Convert a dataclass instance to JSON:

 ```python
 person = Person(name="John Doe", age=30, email="john.doe@example.com")
 json_data = person.to_json()
 print(json_data)
 ```

 Output:

 ```json
 {
     "name": "John Doe",
     "age": 30,
     "email": "john.doe@example.com",
     "phone_numbers": []
 }
 ```

 Parse a JSON string back to a dataclass instance:

 ```python
 person_from_json = Person.from_json(json_data)
 print(person_from_json)
 ```

 ### JSONB Serialization

 Convert a dataclass instance to JSONB:

 ```python
 jsonb_data = person.to_jsonb()
 print(jsonb_data)
 ```

 Output:

 ```json
 {"name":"John Doe","age":30,"email":"john.doe@example.com","phone_numbers":[]}
 ```

 Parse a JSONB string back to a dataclass instance:

 ```python
 person_from_jsonb = Person.from_jsonb(jsonb_data)
 print(person_from_jsonb)
 ```

 ### Proto Serialization

 Generate a Proto definition from a dataclass:

 ```python
 proto_definition = person.to_proto()
 print(proto_definition)
 ```

 Output:

 ```protobuf
 syntax = "proto3";

 message Person {
   string name = 1;
   int32 age = 2;
   string email = 3;
   repeated string phone_numbers = 4;
 }
 ```

 ### Custom Validation

 You can define custom validation logic for fields in your dataclasses using `validation_<field>` methods. These methods will automatically be called during initialization.

 ```python
 @dataclass
 class Address(BaseModel):
     street: str
     city: str
     zip_code: str

     def validation_zip_code(self):
         if not self.zip_code.isdigit() or len(self.zip_code) != 5:
             raise ValueError("Zip code must be a 5-digit number.")
 ```

 ### Defining a gRPC Service

 The `Service` class allows you to define gRPC services with various RPC types.

 ```python
 from transmutate.service import Service, RpcType
 from typing import List

 class TestMessage(BaseModel):
     name: str
     age: int
     email: str
     phone_numbers: List[str]

 class AnotherMessage(BaseModel):
     status: str
     message: str

 service = Service(
     name="TestService",
     types=[RpcType.UNARY, RpcType.SERVER_STREAMING],
     method_names=["GetInfo", "StreamInfo"],
     request_dataclass=TestMessage,
     response_dataclass=AnotherMessage
 )
 ```

 ### Proto File Generation

 Use `ProtoGenerator` to automatically generate Proto files for services and messages.

 ```python
 from transmutate.proto_generator import ProtoGenerator

 services = [
     Service(
         name="TestService",
         types=[RpcType.UNARY, RpcType.SERVER_STREAMING],
         method_names=["GetInfo", "StreamInfo"],
         request_dataclass=TestMessage,
         response_dataclass=AnotherMessage
     )
 ]

 proto_generator = ProtoGenerator(service_name="TestService", services=services)
 proto_generator.generate_proto()
 ```

 Output Proto file will be saved in the specified directory:

 ```
 syntax = "proto3";

 package testservice;

 service TestService {
   rpc GetInfo (TestMessage) returns (AnotherMessage);
   rpc StreamInfo (TestMessage) returns (stream AnotherMessage);
 }

 message TestMessage {
   string name = 1;
   int32 age = 2;
   string email = 3;
   repeated string phone_numbers = 4;
 }

 message AnotherMessage {
   string status = 1;
   string message = 2;
 }
 ```

 ### Testing

 Transmutate includes a suite of unit tests to ensure functionality. You can run the tests using `unittest` or `pytest`.

 ```bash
 # Using unittest
 poetry run python -m unittest discover tests

 # Using pytest
 poetry run pytest tests
 ```

 ## Contributing

 Contributions to Transmutate are welcome! Please feel free to open issues or submit pull requests on the GitHub repository.

 ## License

 Transmutate is open-source software licensed under the MIT License.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "transmutate",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Ali Tavallaie",
    "author_email": "a.tavallaie@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/a7/f6/6c3ee48fb86b25a9b74c8eeaf2db0e84425a0e6a037a8df3aa51b2e04bc2/transmutate-0.2.2.tar.gz",
    "platform": null,
    "description": "[![DOI](https://zenodo.org/badge/837882085.svg)](https://zenodo.org/doi/10.5281/zenodo.13226541)\n# Transmutate\n\n Transmutate is a Python library designed to handle dataclass serialization and deserialization across various formats such as JSON, JSONB, and Protocol Buffers (Proto). The library supports both conversion to these formats and validation of dataclass fields.\n\n ## Features\n\n - **JSON Serialization**: Convert dataclasses to and from JSON format.\n - **JSONB Serialization**: Convert dataclasses to and from JSONB format, a compact version of JSON.\n - **Protocol Buffers Serialization**: Generate Proto definitions from dataclasses.\n - **Field Validation**: Custom validation for dataclass fields using `validation_<field>` methods.\n - **Service Definitions**: Define gRPC services with customizable RPC methods.\n - **Proto Generator**: Automatically generate Proto files including service and message definitions.\n - **Easy Integration**: Built on top of Python's dataclasses, allowing seamless integration with existing codebases.\n\n ## Installation\n\n You can install Transmutate via Poetry by adding it to your `pyproject.toml` file or by using the following command:\n\n ```bash\n poetry add transmutate\n ```\n\n Alternatively, if you're using pip, you can install it with:\n\n ```bash\n pip install transmutate\n ```\n\n ## Usage\n\n Below are some examples demonstrating how to use Transmutate with simple dataclasses.\n\n ### Defining a Dataclass\n\n You can define your dataclasses using the `BaseModel` from Transmutate, which provides built-in serialization and validation capabilities.\n\n ```python\n from dataclasses import dataclass, field\n from typing import List, Optional\n from transmutate.base_model import BaseModel\n\n class Person(BaseModel):\n     name: str\n     age: int\n     email: Optional[str] = None\n     phone_numbers: List[str] = field(default_factory=list)\n\n     def validation_age(self):\n         if not (0 <= self.age <= 120):\n             raise ValueError(\"Age must be between 0 and 120.\")\n\n     def validation_email(self):\n         if self.email and \"@\" not in self.email:\n             raise ValueError(\"Invalid email address.\")\n ```\n\n ### JSON Serialization\n\n Convert a dataclass instance to JSON:\n\n ```python\n person = Person(name=\"John Doe\", age=30, email=\"john.doe@example.com\")\n json_data = person.to_json()\n print(json_data)\n ```\n\n Output:\n\n ```json\n {\n     \"name\": \"John Doe\",\n     \"age\": 30,\n     \"email\": \"john.doe@example.com\",\n     \"phone_numbers\": []\n }\n ```\n\n Parse a JSON string back to a dataclass instance:\n\n ```python\n person_from_json = Person.from_json(json_data)\n print(person_from_json)\n ```\n\n ### JSONB Serialization\n\n Convert a dataclass instance to JSONB:\n\n ```python\n jsonb_data = person.to_jsonb()\n print(jsonb_data)\n ```\n\n Output:\n\n ```json\n {\"name\":\"John Doe\",\"age\":30,\"email\":\"john.doe@example.com\",\"phone_numbers\":[]}\n ```\n\n Parse a JSONB string back to a dataclass instance:\n\n ```python\n person_from_jsonb = Person.from_jsonb(jsonb_data)\n print(person_from_jsonb)\n ```\n\n ### Proto Serialization\n\n Generate a Proto definition from a dataclass:\n\n ```python\n proto_definition = person.to_proto()\n print(proto_definition)\n ```\n\n Output:\n\n ```protobuf\n syntax = \"proto3\";\n\n message Person {\n   string name = 1;\n   int32 age = 2;\n   string email = 3;\n   repeated string phone_numbers = 4;\n }\n ```\n\n ### Custom Validation\n\n You can define custom validation logic for fields in your dataclasses using `validation_<field>` methods. These methods will automatically be called during initialization.\n\n ```python\n @dataclass\n class Address(BaseModel):\n     street: str\n     city: str\n     zip_code: str\n\n     def validation_zip_code(self):\n         if not self.zip_code.isdigit() or len(self.zip_code) != 5:\n             raise ValueError(\"Zip code must be a 5-digit number.\")\n ```\n\n ### Defining a gRPC Service\n\n The `Service` class allows you to define gRPC services with various RPC types.\n\n ```python\n from transmutate.service import Service, RpcType\n from typing import List\n\n class TestMessage(BaseModel):\n     name: str\n     age: int\n     email: str\n     phone_numbers: List[str]\n\n class AnotherMessage(BaseModel):\n     status: str\n     message: str\n\n service = Service(\n     name=\"TestService\",\n     types=[RpcType.UNARY, RpcType.SERVER_STREAMING],\n     method_names=[\"GetInfo\", \"StreamInfo\"],\n     request_dataclass=TestMessage,\n     response_dataclass=AnotherMessage\n )\n ```\n\n ### Proto File Generation\n\n Use `ProtoGenerator` to automatically generate Proto files for services and messages.\n\n ```python\n from transmutate.proto_generator import ProtoGenerator\n\n services = [\n     Service(\n         name=\"TestService\",\n         types=[RpcType.UNARY, RpcType.SERVER_STREAMING],\n         method_names=[\"GetInfo\", \"StreamInfo\"],\n         request_dataclass=TestMessage,\n         response_dataclass=AnotherMessage\n     )\n ]\n\n proto_generator = ProtoGenerator(service_name=\"TestService\", services=services)\n proto_generator.generate_proto()\n ```\n\n Output Proto file will be saved in the specified directory:\n\n ```\n syntax = \"proto3\";\n\n package testservice;\n\n service TestService {\n   rpc GetInfo (TestMessage) returns (AnotherMessage);\n   rpc StreamInfo (TestMessage) returns (stream AnotherMessage);\n }\n\n message TestMessage {\n   string name = 1;\n   int32 age = 2;\n   string email = 3;\n   repeated string phone_numbers = 4;\n }\n\n message AnotherMessage {\n   string status = 1;\n   string message = 2;\n }\n ```\n\n ### Testing\n\n Transmutate includes a suite of unit tests to ensure functionality. You can run the tests using `unittest` or `pytest`.\n\n ```bash\n # Using unittest\n poetry run python -m unittest discover tests\n\n # Using pytest\n poetry run pytest tests\n ```\n\n ## Contributing\n\n Contributions to Transmutate are welcome! Please feel free to open issues or submit pull requests on the GitHub repository.\n\n ## License\n\n Transmutate is open-source software licensed under the MIT License.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A versatile library for transforming and serializing data models into multiple formats.",
    "version": "0.2.2",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3720d66708034f6cddca44638b83cb9e58906e375461f268966faf5782cef780",
                "md5": "0fed2efe296bad2bcdc8251e1da9d82a",
                "sha256": "43c9138ef040b7b5b9fe9af1ff766ba3a2a256755281fb40a726ad30400b4fd9"
            },
            "downloads": -1,
            "filename": "transmutate-0.2.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0fed2efe296bad2bcdc8251e1da9d82a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 9396,
            "upload_time": "2024-08-12T15:23:32",
            "upload_time_iso_8601": "2024-08-12T15:23:32.879599Z",
            "url": "https://files.pythonhosted.org/packages/37/20/d66708034f6cddca44638b83cb9e58906e375461f268966faf5782cef780/transmutate-0.2.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a7f66c3ee48fb86b25a9b74c8eeaf2db0e84425a0e6a037a8df3aa51b2e04bc2",
                "md5": "2d387db04b3bac744795baa186dbcf0e",
                "sha256": "74d32b2a8adfa2cfaa69bbaca4af8627a7929e9322e8d117e450f9755cc68962"
            },
            "downloads": -1,
            "filename": "transmutate-0.2.2.tar.gz",
            "has_sig": false,
            "md5_digest": "2d387db04b3bac744795baa186dbcf0e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 8684,
            "upload_time": "2024-08-12T15:23:34",
            "upload_time_iso_8601": "2024-08-12T15:23:34.861050Z",
            "url": "https://files.pythonhosted.org/packages/a7/f6/6c3ee48fb86b25a9b74c8eeaf2db0e84425a0e6a037a8df3aa51b2e04bc2/transmutate-0.2.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-08-12 15:23:34",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "transmutate"
}
        
Elapsed time: 5.07885s