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

1541 UUID bytes support for 16 byte strings / BINARY(16) #1542

Merged
merged 3 commits into from May 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/1541-shawnwall.md
@@ -0,0 +1 @@
Added support for UUID instantiation through 16 byte strings such as `b'\x12\x34\x56\x78' * 4`. This was done to support `BINARY(16)` columns in sqlalchemy.
2 changes: 1 addition & 1 deletion docs/usage/types.md
Expand Up @@ -145,7 +145,7 @@ with custom properties and validation.
see [Pydantic Types](#pydantic-types) for other more strict path types

`uuid.UUID`
: strings and bytes (converted to strings) are passed to `UUID(v)`;
: strings and bytes (converted to strings) are passed to `UUID(v)`, with a fallback to `UUID(bytes=v)` for `bytes` and `bytearray`;
see [Pydantic Types](#pydantic-types) for other stricter UUID types

`ByteSize`
Expand Down
7 changes: 6 additions & 1 deletion pydantic/validators.py
Expand Up @@ -252,7 +252,12 @@ def uuid_validator(v: Any, field: 'ModelField') -> UUID:
if isinstance(v, str):
v = UUID(v)
elif isinstance(v, (bytes, bytearray)):
v = UUID(v.decode())
try:
v = UUID(v.decode())
except ValueError:
# 16 bytes in big-endian order as the bytes argument fail
# the above check
v = UUID(bytes=v)
except ValueError:
raise errors.UUIDError()

Expand Down
1 change: 1 addition & 0 deletions tests/test_types.py
Expand Up @@ -392,6 +392,7 @@ def __bool__(self) -> bool:
('uuid_check', 'ebcdab58-6eb8-46fb-a190-d07a33e9eac8', UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8')),
('uuid_check', UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8'), UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8')),
('uuid_check', b'ebcdab58-6eb8-46fb-a190-d07a33e9eac8', UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8')),
('uuid_check', b'\x12\x34\x56\x78' * 4, UUID('12345678-1234-5678-1234-567812345678')),
('uuid_check', 'ebcdab58-6eb8-46fb-a190-', ValidationError),
('uuid_check', 123, ValidationError),
('decimal_check', 42.24, Decimal('42.24')),
Expand Down