processor.py 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # -*- coding: utf-8 -*-
  2. import typing
  3. from hapic.exception import InputValidationException, OutputValidationException
  4. class RequestParameters(object):
  5. def __init__(
  6. self,
  7. path_parameters,
  8. query_parameters,
  9. body_parameters,
  10. form_parameters,
  11. header_parameters,
  12. ):
  13. self.path_parameters = path_parameters
  14. self.query_parameters = query_parameters
  15. self.body_parameters = body_parameters
  16. self.form_parameters = form_parameters
  17. self.header_parameters = header_parameters
  18. class ProcessValidationError(object):
  19. def __init__(
  20. self,
  21. error_message: str,
  22. error_details: dict,
  23. ) -> None:
  24. self.error_message = error_message
  25. self.error_details = error_details
  26. class ProcessorInterface(object):
  27. def __init__(self):
  28. self.schema = None
  29. def process(self, value):
  30. raise NotImplementedError
  31. def get_validation_error(
  32. self,
  33. request_context: RequestParameters,
  34. ) -> ProcessValidationError:
  35. raise NotImplementedError
  36. class InputProcessor(ProcessorInterface):
  37. pass
  38. class OutputProcessor(ProcessorInterface):
  39. pass
  40. class MarshmallowOutputProcessor(OutputProcessor):
  41. def process(self, data: typing.Any):
  42. data = self.schema.dump(data).data
  43. self.validate(data)
  44. return data
  45. def validate(self, data: typing.Any) -> None:
  46. errors = self.schema.load(data).errors
  47. if errors:
  48. raise OutputValidationException(
  49. 'Error when validate input: {}'.format(
  50. str(errors),
  51. )
  52. )
  53. def get_validation_error(self, data: dict) -> ProcessValidationError:
  54. data = self.schema.dump(data).data
  55. errors = self.schema.load(data).errors
  56. return ProcessValidationError(
  57. error_message='Validation error of output data',
  58. error_details=errors,
  59. )
  60. class MarshmallowInputProcessor(InputProcessor):
  61. def process(self, data: dict):
  62. unmarshall = self.schema.load(data)
  63. if unmarshall.errors:
  64. raise OutputValidationException(
  65. 'Error when validate ouput: {}'.format(
  66. str(unmarshall.errors),
  67. )
  68. )
  69. return unmarshall.data
  70. def get_validation_error(self, data: dict) -> ProcessValidationError:
  71. marshmallow_errors = self.schema.load(data).errors
  72. return ProcessValidationError(
  73. error_message='Validation error of input data',
  74. error_details=marshmallow_errors,
  75. )