-
Notifications
You must be signed in to change notification settings - Fork 63
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
Added in a new object id field for mongodb #151
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
from typing import Any | ||
|
||
try: | ||
from bson import ObjectId | ||
except ModuleNotFoundError: # pragma: no cover | ||
raise RuntimeError( | ||
'The `ObjectIdField` module requires "bson" to be installed. You can install it with "pip install ' | ||
'bson".' | ||
) | ||
from pydantic_core import core_schema | ||
from pydantic_core import PydanticCustomError | ||
|
||
|
||
class ObjectIdField(str): | ||
SkandaPrasad-S marked this conversation as resolved.
Show resolved
Hide resolved
|
||
@classmethod | ||
def __get_pydantic_core_schema__( | ||
cls, _source_type: Any, _handler: Any | ||
) -> core_schema.CoreSchema: | ||
object_id_schema = core_schema.chain_schema( | ||
[ | ||
core_schema.str_schema(), | ||
core_schema.no_info_plain_validator_function(cls.validate), | ||
] | ||
) | ||
return core_schema.json_or_python_schema( | ||
json_schema=object_id_schema, | ||
python_schema=core_schema.union_schema( | ||
[core_schema.is_instance_schema(ObjectId), object_id_schema] | ||
), | ||
serialization=core_schema.plain_serializer_function_ser_schema( | ||
lambda x: str(x) | ||
), | ||
) | ||
|
||
@classmethod | ||
def validate(cls, value): | ||
try: | ||
return ObjectId(value) | ||
except bson.errors.InvalidId as invalid_id: | ||
raise PydanticCustomError('value_error', 'invalid format for MongoDB object identifier') from invalid_id |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -49,7 +49,8 @@ all = [ | |
'pycountry>=23', | ||
'python-ulid>=1,<2; python_version<"3.9"', | ||
'python-ulid>=1,<3; python_version>="3.9"', | ||
'pendulum>=3.0.0,<4.0.0' | ||
'pendulum>=3.0.0,<4.0.0', | ||
'bson>=0.5; python_version>="3.9"', | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. But here for sure should be |
||
] | ||
|
||
[project.urls] | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import pytest | ||
from pydantic import BaseModel, ValidationError | ||
|
||
from pydantic_extra_types.mongo_objectId import ObjectIdField | ||
|
||
|
||
class Something(BaseModel): | ||
object_id: ObjectIdField | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"object_id, result, valid", | ||
[ | ||
# Valid ObjectId for str format | ||
("611827f2878b88b49ebb69fc", "611827f2878b88b49ebb69fc", True), | ||
("611827f2878b88b49ebb69fd", "611827f2878b88b49ebb69fd", True), | ||
# Invalid ObjectId for str format | ||
("611827f2878b88b49ebb69f", None, False), # Invalid ObjectId (short length) | ||
("611827f2878b88b49ebb69fca", None, False), # Invalid ObjectId (long length) | ||
# Valid ObjectId for bytes format | ||
], | ||
) | ||
def test_format_for_object_id(object_id, result, valid): | ||
if valid: | ||
assert str(Something(object_id=object_id).object_id) == result | ||
else: | ||
with pytest.raises(ValidationError): | ||
Something(object_id=object_id) | ||
|
||
|
||
def test_json_schema(): | ||
assert Something.model_json_schema(mode="validation") == { | ||
"properties": {"object_id": {"title": "Object Id", "type": "string"}}, | ||
"required": ["object_id"], | ||
"title": "Something", | ||
"type": "object", | ||
} | ||
assert Something.model_json_schema(mode="serialization") == { | ||
"properties": { | ||
"object_id": { | ||
"anyOf": [{"type": "string"}], | ||
"title": "Object Id", | ||
} | ||
}, | ||
"required": ["object_id"], | ||
"title": "Something", | ||
"type": "object", | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think this is correct. It should be
pip install pymongo
. 😅There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Or maybe not mention what should be installed...