aiohttp-swagger
aiohttp-swagger copied to clipboard
`json.dumps` in `swagger_info` will fail on datetime serialization
If the swagger_info attribute contains a datetime object in an example definition, the default JSON serializer will fail for datetime types.
ex)
TypeError: datetime.datetime(2021, 11, 14, 1, 34, 26, tzinfo=datetime.timezone(datetime.timedelta(0, 720))) is not JSON serializable
https://swagger.io/docs/specification/data-models/data-types/#string
https://github.com/cr0hn/aiohttp-swagger/blob/ea321152805878abb23040fa5c7186b89d872b38/aiohttp_swagger/init.py#L75
Proposing a PR to either:
- allow the caller to pass in a string, a pre-serialized spec;
- allow the caller to specify a user-defined serializer function; or
- something else.
In my case, changing all the json.dumps calls and adding default=str as an argument solved the issue.
Since this project seems unmaintained at the moment, I've added the following lines to my Dockerfile to patch the library for this issue:
LIB_FOLDER=$(python -c 'import aiohttp_swagger; print(aiohttp_swagger.__path__[0])')
sed -i 's/json.dumps(swagger)/json.dumps(swagger, default=str)/g' $LIB_FOLDER/helpers/builders.py
sed -i 's/json.dumps(swagger_info)/json.dumps(swagger_info, default=str)/g' $LIB_FOLDER/__init__.py
Or via monkey patching:
aiohttp_swagger.json.dumps = partial(aiohttp_swagger.json.dumps, default=str)
aiohttp_swagger.helpers.builders.json.dumps = partial(aiohttp_swagger.helpers.builders.json.dumps, default=str)