Metadata-Version: 2.4
Name: pydantic-fixedwidth
Version: 0.3.0
Summary: Custom Pydantic models for parsing and serializing fixed-width format of data.
Project-URL: Homepage, https://github.com/lasuillard-s/pydantic-fixedwidth
Project-URL: Repository, https://github.com/lasuillard-s/pydantic-fixedwidth.git
Project-URL: Issues, https://github.com/lasuillard-s/pydantic-fixedwidth/issues
License-Expression: MIT
License-File: LICENSE
Requires-Python: <4.0,>=3.10
Requires-Dist: pydantic<3,>=2
Description-Content-Type: text/markdown

# pydantic-fixedwidth

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![codecov](https://codecov.io/gh/lasuillard-s/pydantic-fixedwidth/graph/badge.svg?token=R5pQWB43DP)](https://codecov.io/gh/lasuillard-s/pydantic-fixedwidth)
[![PyPI - Version](https://img.shields.io/pypi/v/pydantic-fixedwidth)](https://pypi.org/project/pydantic-fixedwidth/)

Custom Pydantic models for serializing and deserializing fixed-width format data.


## 🚀 Quick Start

Install this package with pip:

```shell
$ pip install pydantic-fixedwidth
```

Usage example:

```python
from datetime import datetime, timezone

from pydantic_fixedwidth import Fixedwidth, Padding
from pydantic_fixedwidth import OrderedField as Field

tzinfo = timezone.utc


class SomeRequest(Fixedwidth):
    string: str = Field(length=8)
    hangul: str = Field(length=6)
    number: int = Field(length=10, justify="right", fill_char=b"0")

    # Just an padding field
    p_: str = Padding(length=10)

    # This field will be ignored in ser/de
    ignore: str = Field(length=10, default="IGNORE", exclude=True)

    ts: datetime = Field(
        length=20,
        to_str=lambda dt: dt.strftime("%Y%m%d%H%M%S%f"),
        from_str=lambda s: datetime.strptime(s, "%Y%m%d%H%M%S%f").replace(tzinfo=tzinfo),
    )


# Format model to bytes
some_request = SomeRequest(
    string="<DFG&",
    hangul="한글",
    number=381,
    ts=datetime(2024, 1, 23, 14, 11, 20, 124277, tzinfo=tzinfo),
)
b = some_request.format_bytes()

assert len(b) == 54
assert b == b"<DFG&   \xed\x95\x9c\xea\xb8\x800000000381          20240123141120124277"

# Parse bytes into model
parsed_request = SomeRequest.parse_bytes(b)

assert parsed_request == some_request
```
