-
Notifications
You must be signed in to change notification settings - Fork 291
Add UUID validator #584
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
Add UUID validator #584
Changes from all commits
d8b9b3e
93103c1
e8b7ce1
fedac0f
0b06fb7
dba435a
9f7e356
3562f0c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3503,6 +3503,38 @@ def multi_host_url_schema( | |
) | ||
|
||
|
||
class UuidSchema(TypedDict, total=False): | ||
type: Required[Literal['uuid']] | ||
version: int | ||
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. I'm guessing this should be something like 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. I think we should at least have Note that Python doesn't support generating UUID v2 and nor does the rust 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. I'm guessing this should be something like |
||
ref: str | ||
metadata: Any | ||
serialization: SerSchema | ||
|
||
|
||
def uuid_schema( | ||
*, version: int | None = None, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None | ||
) -> UuidSchema: | ||
""" | ||
Returns a schema that matches a UUID value, e.g.: | ||
|
||
```py | ||
from pydantic_core import SchemaValidator, core_schema | ||
|
||
schema = core_schema.uuid_schema() | ||
v = SchemaValidator(schema) | ||
print(v.validate_python('12345678-1234-5678-1234-567812345678')) | ||
#> 12345678-1234-5678-1234-567812345678 | ||
``` | ||
|
||
Args: | ||
version: The UUID version number as per RFC 4122 | ||
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. say what it defaults to if ommitted. |
||
ref: optional unique identifier of the schema, used to reference the schema in other places | ||
metadata: Any other information you want to include with the schema, not used by pydantic-core | ||
serialization: Custom serialization schema | ||
""" | ||
return dict_not_none(type='uuid', version=version, ref=ref, metadata=metadata, serialization=serialization) | ||
|
||
|
||
class DefinitionsSchema(TypedDict, total=False): | ||
type: Required[Literal['definitions']] | ||
schema: Required[CoreSchema] | ||
|
@@ -3613,6 +3645,7 @@ def definition_reference_schema( | |
JsonSchema, | ||
UrlSchema, | ||
MultiHostUrlSchema, | ||
UuidSchema, | ||
DefinitionsSchema, | ||
DefinitionReferenceSchema, | ||
] | ||
|
@@ -3665,6 +3698,7 @@ def definition_reference_schema( | |
'json', | ||
'url', | ||
'multi-host-url', | ||
'uuid', | ||
'definitions', | ||
'definition-ref', | ||
] | ||
|
@@ -3757,4 +3791,7 @@ def definition_reference_schema( | |
'url_syntax_violation', | ||
'url_too_long', | ||
'url_scheme', | ||
'uuid_type', | ||
'uuid_parsing', | ||
'uuid_version_mismatch', | ||
] |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -294,6 +294,16 @@ pub enum ErrorType { | |||||
UrlScheme { | ||||||
expected_schemes: String, | ||||||
}, | ||||||
// --------------------- | ||||||
// UUID errors | ||||||
UuidType, | ||||||
UuidParsing { | ||||||
error: String, | ||||||
}, | ||||||
UuidVersionMismatch { | ||||||
version: usize, | ||||||
schema_version: usize, | ||||||
}, | ||||||
} | ||||||
|
||||||
macro_rules! render { | ||||||
|
@@ -432,6 +442,10 @@ impl ErrorType { | |||||
Self::UrlSyntaxViolation { .. } => extract_context!(Cow::Owned, UrlSyntaxViolation, ctx, error: String), | ||||||
Self::UrlTooLong { .. } => extract_context!(UrlTooLong, ctx, max_length: usize), | ||||||
Self::UrlScheme { .. } => extract_context!(UrlScheme, ctx, expected_schemes: String), | ||||||
Self::UuidParsing { .. } => extract_context!(UuidParsing, ctx, error: String), | ||||||
Self::UuidVersionMismatch { .. } => { | ||||||
extract_context!(UuidVersionMismatch, ctx, version: usize, schema_version: usize) | ||||||
} | ||||||
_ => { | ||||||
if ctx.is_some() { | ||||||
py_err!(PyTypeError; "'{}' errors do not require context", value) | ||||||
|
@@ -533,6 +547,9 @@ impl ErrorType { | |||||
Self::UrlSyntaxViolation {..} => "Input violated strict URL syntax rules, {error}", | ||||||
Self::UrlTooLong {..} => "URL should have at most {max_length} characters", | ||||||
Self::UrlScheme {..} => "URL scheme should be {expected_schemes}", | ||||||
Self::UuidType => "Input should be a string", | ||||||
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.
Suggested change
or something, you'll also want a custom error message for JSON, see the function below. |
||||||
Self::UuidParsing {..} => "Input should be a valid UUID, {error}", | ||||||
Self::UuidVersionMismatch {..} => "UUID version {version} does not match expected version: {schema_version}", | ||||||
} | ||||||
} | ||||||
|
||||||
|
@@ -632,6 +649,11 @@ impl ErrorType { | |||||
Self::UrlSyntaxViolation { error } => render!(tmpl, error), | ||||||
Self::UrlTooLong { max_length } => to_string_render!(tmpl, max_length), | ||||||
Self::UrlScheme { expected_schemes } => render!(tmpl, expected_schemes), | ||||||
Self::UuidParsing { error } => render!(tmpl, error), | ||||||
Self::UuidVersionMismatch { | ||||||
version, | ||||||
schema_version, | ||||||
} => to_string_render!(tmpl, version, schema_version), | ||||||
_ => Ok(tmpl.to_string()), | ||||||
} | ||||||
} | ||||||
|
@@ -689,6 +711,11 @@ impl ErrorType { | |||||
Self::UrlSyntaxViolation { error } => py_dict!(py, error), | ||||||
Self::UrlTooLong { max_length } => py_dict!(py, max_length), | ||||||
Self::UrlScheme { expected_schemes } => py_dict!(py, expected_schemes), | ||||||
Self::UuidParsing { error } => py_dict!(py, error), | ||||||
Self::UuidVersionMismatch { | ||||||
version, | ||||||
schema_version, | ||||||
} => py_dict!(py, version, schema_version), | ||||||
_ => Ok(None), | ||||||
} | ||||||
} | ||||||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
use std::borrow::Cow; | ||
|
||
use pyo3::prelude::*; | ||
use pyo3::types::PyDict; | ||
|
||
use crate::definitions::DefinitionsBuilder; | ||
use crate::uuid::PyUuid; | ||
|
||
use super::{ | ||
infer_json_key, infer_serialize, infer_to_python, BuildSerializer, CombinedSerializer, Extra, SerMode, | ||
TypeSerializer, | ||
}; | ||
|
||
#[derive(Debug, Clone)] | ||
pub struct UuidSerializer; | ||
|
||
impl BuildSerializer for UuidSerializer { | ||
const EXPECTED_TYPE: &'static str = "uuid"; | ||
|
||
fn build( | ||
_schema: &PyDict, | ||
_config: Option<&PyDict>, | ||
_definitions: &mut DefinitionsBuilder<CombinedSerializer>, | ||
) -> PyResult<CombinedSerializer> { | ||
Ok(Self {}.into()) | ||
} | ||
} | ||
|
||
impl TypeSerializer for UuidSerializer { | ||
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. I'm not sure you need this, the existing 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. I'm not sure you need this, the existing 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. I'm not sure you need this, the existing |
||
fn to_python( | ||
&self, | ||
value: &PyAny, | ||
include: Option<&PyAny>, | ||
exclude: Option<&PyAny>, | ||
extra: &Extra, | ||
) -> PyResult<PyObject> { | ||
let py = value.py(); | ||
match value.extract::<PyUuid>() { | ||
Ok(py_uuid) => match extra.mode { | ||
SerMode::Json => Ok(py_uuid.__str__().into_py(py)), | ||
_ => Ok(value.into_py(py)), | ||
}, | ||
Err(_) => { | ||
extra.warnings.on_fallback_py(self.get_name(), value, extra)?; | ||
infer_to_python(value, include, exclude, extra) | ||
} | ||
} | ||
} | ||
|
||
fn json_key<'py>(&self, key: &'py PyAny, extra: &Extra) -> PyResult<Cow<'py, str>> { | ||
match key.extract::<PyUuid>() { | ||
Ok(py_uuid) => Ok(Cow::Owned(py_uuid.__str__())), | ||
Err(_) => { | ||
extra.warnings.on_fallback_py(self.get_name(), key, extra)?; | ||
infer_json_key(key, extra) | ||
} | ||
} | ||
} | ||
|
||
fn serde_serialize<S: serde::ser::Serializer>( | ||
&self, | ||
value: &PyAny, | ||
serializer: S, | ||
include: Option<&PyAny>, | ||
exclude: Option<&PyAny>, | ||
extra: &Extra, | ||
) -> Result<S::Ok, S::Error> { | ||
match value.extract::<PyUuid>() { | ||
Ok(py_uuid) => serializer.serialize_str(&py_uuid.__str__()), | ||
Err(_) => { | ||
extra.warnings.on_fallback_ser::<S>(self.get_name(), value, extra)?; | ||
infer_serialize(value, serializer, include, exclude, extra) | ||
} | ||
} | ||
} | ||
|
||
fn get_name(&self) -> &str { | ||
Self::EXPECTED_TYPE | ||
} | ||
} |
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.
__init__
should come first.