diff --git a/AUTHORS.rst b/AUTHORS.rst index 17bea2b9..539d3e9f 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -78,3 +78,4 @@ Contributors (chronological) - Mounier Florian `@paradoxxxzero `_ - Renato Damas `@codectl `_ - Tayler Sokalski `@tsokalski `_ +- Sebastien Lovergne `@TheBigRoomXXL `_ diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 05dc58a2..c7b07a21 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -4,6 +4,12 @@ Changelog 6.4.0 (unreleased) ****************** +Features: + +- ``MarshmallowPlugin``: Support different datetime formats + for ``marshmallow.fields.DateTime`` fields (:issue:`814`). + Thanks :user:`TheBigRoomXXL` for the suggestion and PR. + Other changes: - Support Python 3.12. diff --git a/docs/using_plugins.rst b/docs/using_plugins.rst index 369fa227..c00d3e61 100644 --- a/docs/using_plugins.rst +++ b/docs/using_plugins.rst @@ -236,6 +236,22 @@ Schema Modifiers apispec will respect schema modifiers such as ``exclude`` and ``partial`` in the generated schema definition. If a schema is initialized with modifiers, apispec will treat each combination of modifiers as a unique schema definition. +Custom DateTime formats +*********************** + +apispec supports all four basic formats of `marshmallow.fields.DateTime`: ``"rfc"`` (for RFC822), ``"iso"`` (for ISO8601), +``"timestamp"``, ``"timestamp_ms"`` (for a POSIX timestamp). + +If you are using a custom DateTime format you should pass a regex string to the ``pattern`` parameter in your field ``metadata`` so that it is included as documentation. + +.. code-block:: python + + class SchemaWithCustomDate(Schema): + french_date = ma.DateTime( + format="%d-%m%Y %H:%M:%S", + metadata={"pattern": r"^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}$"}, + ) + Custom Fields ************* diff --git a/src/apispec/ext/marshmallow/field_converter.py b/src/apispec/ext/marshmallow/field_converter.py index 2bf8a9de..79fd368e 100644 --- a/src/apispec/ext/marshmallow/field_converter.py +++ b/src/apispec/ext/marshmallow/field_converter.py @@ -110,6 +110,7 @@ def init_attribute_functions(self): self.list2properties, self.dict2properties, self.timedelta2properties, + self.datetime2properties, ] def map_to_openapi_type(self, field_cls, *args): @@ -518,6 +519,53 @@ def enum2properties(self, field, **kwargs: typing.Any) -> dict: ret["enum"] = [field.field._serialize(v, None, None) for v in choices] return ret + def datetime2properties(self, field, **kwargs: typing.Any) -> dict: + """Return a dictionary of properties from :class:`DateTime