2020-01-13 15:37:12 +00:00
|
|
|
"""OpenAPI core contrib flask handlers module"""
|
|
|
|
from flask.globals import current_app
|
|
|
|
from flask.json import dumps
|
|
|
|
|
2021-03-30 12:09:39 +00:00
|
|
|
from openapi_core.templating.media_types.exceptions import MediaTypeNotFound
|
2020-02-21 16:33:45 +00:00
|
|
|
from openapi_core.templating.paths.exceptions import (
|
|
|
|
ServerNotFound, OperationNotFound, PathNotFound,
|
|
|
|
)
|
2020-01-13 15:37:12 +00:00
|
|
|
|
|
|
|
|
|
|
|
class FlaskOpenAPIErrorsHandler(object):
|
|
|
|
|
|
|
|
OPENAPI_ERROR_STATUS = {
|
2020-02-21 16:33:45 +00:00
|
|
|
ServerNotFound: 400,
|
|
|
|
OperationNotFound: 405,
|
|
|
|
PathNotFound: 404,
|
2021-03-30 12:09:39 +00:00
|
|
|
MediaTypeNotFound: 415,
|
2020-01-13 15:37:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def handle(cls, errors):
|
|
|
|
data_errors = [
|
|
|
|
cls.format_openapi_error(err)
|
|
|
|
for err in errors
|
|
|
|
]
|
|
|
|
data = {
|
|
|
|
'errors': data_errors,
|
|
|
|
}
|
2020-02-18 11:51:42 +00:00
|
|
|
data_error_max = max(data_errors, key=lambda x: x['status'])
|
|
|
|
status = data_error_max['status']
|
2020-01-13 15:37:12 +00:00
|
|
|
return current_app.response_class(
|
|
|
|
dumps(data),
|
|
|
|
status=status,
|
|
|
|
mimetype='application/json'
|
|
|
|
)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def format_openapi_error(cls, error):
|
|
|
|
return {
|
|
|
|
'title': str(error),
|
|
|
|
'status': cls.OPENAPI_ERROR_STATUS.get(error.__class__, 400),
|
|
|
|
'class': str(type(error)),
|
|
|
|
}
|