context.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import re
  4. import typing
  5. try: # Python 3.5+
  6. from http import HTTPStatus
  7. except ImportError:
  8. from http import client as HTTPStatus
  9. from hapic.context import BaseContext
  10. from hapic.context import RouteRepresentation
  11. from hapic.decorator import DecoratedController
  12. from hapic.decorator import DECORATION_ATTRIBUTE_NAME
  13. from hapic.exception import OutputValidationException
  14. from hapic.processor import RequestParameters
  15. from hapic.processor import ProcessValidationError
  16. from hapic.error import DefaultErrorBuilder
  17. from hapic.error import ErrorBuilderInterface
  18. if typing.TYPE_CHECKING:
  19. from pyramid.response import Response
  20. from pyramid.config import Configurator
  21. # Bottle regular expression to locate url parameters
  22. PYRAMID_RE_PATH_URL = re.compile(r'')
  23. class PyramidContext(BaseContext):
  24. def __init__(
  25. self,
  26. configurator: 'Configurator',
  27. default_error_builder: ErrorBuilderInterface = None,
  28. ):
  29. self.configurator = configurator
  30. self.default_error_builder = \
  31. default_error_builder or DefaultErrorBuilder() # FDV
  32. def get_request_parameters(self, *args, **kwargs) -> RequestParameters:
  33. req = args[-1] # TODO : Check
  34. # TODO : move this code to check_json
  35. # same idea as in : https://bottlepy.org/docs/dev/_modules/bottle.html#BaseRequest.json
  36. if req.body and req.content_type in ('application/json', 'application/json-rpc'):
  37. json_body = req.json_body
  38. # TODO : raise exception if not correct , return 400 if uncorrect instead ?
  39. else:
  40. json_body = {}
  41. return RequestParameters(
  42. path_parameters=req.matchdict,
  43. query_parameters=req.GET,
  44. body_parameters=json_body,
  45. form_parameters=req.POST,
  46. header_parameters=req.headers,
  47. files_parameters={}, # TODO - G.M - 2017-11-05 - Code it
  48. )
  49. def get_response(
  50. self,
  51. response: str,
  52. http_code: int,
  53. mimetype: str='application/json',
  54. ) -> 'Response':
  55. from pyramid.response import Response
  56. return Response(
  57. body=response,
  58. headers=[
  59. ('Content-Type', mimetype),
  60. ],
  61. status=http_code,
  62. )
  63. def get_validation_error_response(
  64. self,
  65. error: ProcessValidationError,
  66. http_code: HTTPStatus=HTTPStatus.BAD_REQUEST,
  67. ) -> typing.Any:
  68. from pyramid.response import Response
  69. error_content = self.default_error_builder.build_from_validation_error(
  70. error,
  71. )
  72. # Check error
  73. dumped = self.default_error_builder.dump(error).data
  74. unmarshall = self.default_error_builder.load(dumped)
  75. if unmarshall.errors:
  76. raise OutputValidationException(
  77. 'Validation error during dump of error response: {}'.format(
  78. str(unmarshall.errors)
  79. )
  80. )
  81. return Response(
  82. body=json.dumps(error_content),
  83. headers=[
  84. ('Content-Type', 'application/json'),
  85. ],
  86. status=int(http_code),
  87. )
  88. def find_route(
  89. self,
  90. decorated_controller: DecoratedController,
  91. ) -> RouteRepresentation:
  92. for category in self.configurator.introspector.get_category('views'):
  93. view_intr = category['introspectable']
  94. route_intr = category['related']
  95. reference = decorated_controller.reference
  96. route_token = getattr(
  97. view_intr.get('callable'),
  98. DECORATION_ATTRIBUTE_NAME,
  99. None,
  100. )
  101. match_with_wrapper = view_intr.get('callable') == reference.wrapper
  102. match_with_wrapped = view_intr.get('callable') == reference.wrapped
  103. match_with_token = route_token == reference.token
  104. if match_with_wrapper or match_with_wrapped or match_with_token:
  105. # TODO BS 20171107: C'est une liste de route sous pyramid !!!
  106. # Mais de toute maniere les framework womme pyramid, flask
  107. # peuvent avoir un controlleur pour plusieurs routes doc
  108. # .find_route doit retourner une liste au lieu d'une seule
  109. # route
  110. route_pattern = route_intr[0].get('pattern')
  111. route_method = route_intr[0].get('request_methods')[0]
  112. return RouteRepresentation(
  113. rule=self.get_swagger_path(route_pattern),
  114. method=route_method,
  115. original_route_object=route_intr[0],
  116. )
  117. def get_swagger_path(self, contextualised_rule: str) -> str:
  118. # TODO BS 20171110: Pyramid allow route like '/{foo:\d+}', so adapt
  119. # and USE regular expression (see https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html#custom-route-predicates) # nopep8
  120. return contextualised_rule
  121. def by_pass_output_wrapping(self, response: typing.Any) -> bool:
  122. return False