processor.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. unmarshall = self.schema.dump(data)
  43. # TODO: Il n'y a jamais rien dans le error au dump. il faut check le
  44. # data au travers de .validate
  45. if unmarshall.errors:
  46. raise InputValidationException(
  47. 'Error when validate input: {}'.format(
  48. str(unmarshall.errors),
  49. )
  50. )
  51. return unmarshall.data
  52. def get_validation_error(self, data: dict) -> ProcessValidationError:
  53. marshmallow_errors = self.schema.dump(data).errors
  54. return ProcessValidationError(
  55. error_message='Validation error of output data',
  56. error_details=marshmallow_errors,
  57. )
  58. class MarshmallowInputProcessor(OutputProcessor):
  59. def process(self, data: dict):
  60. unmarshall = self.schema.load(data)
  61. if unmarshall.errors:
  62. raise OutputValidationException(
  63. 'Error when validate ouput: {}'.format(
  64. str(unmarshall.errors),
  65. )
  66. )
  67. return unmarshall.data
  68. def get_validation_error(self, data: dict) -> ProcessValidationError:
  69. marshmallow_errors = self.schema.load(data).errors
  70. return ProcessValidationError(
  71. error_message='Validation error of input data',
  72. error_details=marshmallow_errors,
  73. )