Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The "Custom field types" doc talks about a __bson__ method with an example that doesn't include it #469

Open
Terseus opened this issue May 3, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@Terseus
Copy link

Terseus commented May 3, 2024

Bug

In the page about Custom field types we can see the following phrase at the start:

Sometimes, it might be required to customize as well the field BSON serialization. In order to do this, the field class will have to implement the __bson__ class method.

However the it does show this example that, as we can see, doesn't contains any method called __bson__, instead it uses the WithBsonSerializer annotation:

from typing import Annotated
from odmantic import AIOEngine, Model, WithBsonSerializer

class ASCIISerializedAsBinaryBase(str):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if isinstance(v, bytes):  # Handle data coming from MongoDB
            return v.decode("ascii")
        if not isinstance(v, str):
            raise TypeError("string required")
        if not v.isascii():
            raise ValueError("Only ascii characters are allowed")
        return v


def serialize_ascii_to_bytes(v: ASCIISerializedAsBinaryBase) -> bytes:
    # We can encode this string as ascii since it contains
    # only ascii characters
    bytes_ = v.encode("ascii")
    return bytes_


ASCIISerializedAsBinary = Annotated[
    ASCIISerializedAsBinaryBase, WithBsonSerializer(serialize_ascii_to_bytes)
]

class Example(Model):
    field: ASCIISerializedAsBinary

engine = AIOEngine()
await engine.save(Example(field="hello world"))
fetched = await engine.find_one(Example)
print(fetched.field)
#> hello world

Current Behavior

Go to https://art049.github.io/odmantic/fields/#custom-field-types and read the doc.

Expected behavior

The technique described in the doc and the one used in the example should match.

Environment

  • ODMantic version: v1.0.1
  • MongoDB version: N/A
  • Pydantic infos (output of python -c "import pydantic.utils; print(pydantic.utils.version_info())): N/A
  • Version of additional modules (if relevant): N/A
@Terseus Terseus added the bug Something isn't working label May 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant