From c56a7eebf4c72844ddf625ee30d1ca004f48dbbd Mon Sep 17 00:00:00 2001 From: Sebastien LOVERGNE Date: Wed, 15 Feb 2023 09:52:10 +0100 Subject: [PATCH] Add support for the multiple formats of marshmallow.fields.DateTime --- AUTHORS.rst | 1 + docs/using_plugins.rst | 16 ++++ .../ext/marshmallow/field_converter.py | 43 ++++++++++ tests/test_ext_marshmallow_field.py | 85 ++++++++++++++++++- 4 files changed, 141 insertions(+), 4 deletions(-) diff --git a/AUTHORS.rst b/AUTHORS.rst index afe779fb..0195cec0 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -76,3 +76,4 @@ Contributors (chronological) - ``_ - Edwin Erdmanis `@vorticity `_ - Mounier Florian `@paradoxxxzero `_ +- Sebastien Lovergne `@TheBigRoomXXL `_ diff --git a/docs/using_plugins.rst b/docs/using_plugins.rst index 8dd2b4bc..60ea6b2a 100644 --- a/docs/using_plugins.rst +++ b/docs/using_plugins.rst @@ -235,6 +235,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 format +************* + +apispec support 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`` parametter in your field ``metadata``. + +.. 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 20bc56ff..2e5f0c10 100644 --- a/src/apispec/ext/marshmallow/field_converter.py +++ b/src/apispec/ext/marshmallow/field_converter.py @@ -111,6 +111,7 @@ def init_attribute_functions(self): self.list2properties, self.dict2properties, self.timedelta2properties, + self.datetime2properties, ] def map_to_openapi_type(self, field_cls, *args): @@ -516,6 +517,48 @@ 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