Browse Source

Use HandledException class instead tuple

Bastien Sevajol 6 years ago
parent
commit
4d3fc94a73
5 changed files with 36 additions and 25 deletions
  1. 18 5
      hapic/context.py
  2. 6 5
      hapic/ext/bottle/context.py
  3. 2 5
      hapic/ext/flask/context.py
  4. 2 4
      hapic/ext/pyramid/context.py
  5. 8 6
      tests/base.py

+ 18 - 5
hapic/context.py View File

129
         raise NotImplementedError()
129
         raise NotImplementedError()
130
 
130
 
131
 
131
 
132
+class HandledException(object):
133
+    """
134
+    Representation of an handled exception with it's http code
135
+    """
136
+    def __init__(
137
+        self,
138
+        exception_class: typing.Type[Exception],
139
+        http_code: int = 500,
140
+    ):
141
+        self.exception_class = exception_class
142
+        self.http_code = http_code
143
+
144
+
132
 class BaseContext(ContextInterface):
145
 class BaseContext(ContextInterface):
133
     def get_default_error_builder(self) -> ErrorBuilderInterface:
146
     def get_default_error_builder(self) -> ErrorBuilderInterface:
134
         """ see hapic.context.ContextInterface#get_default_error_builder"""
147
         """ see hapic.context.ContextInterface#get_default_error_builder"""
166
             except Exception as exc:
179
             except Exception as exc:
167
                 # Reverse list to read first user given exception before
180
                 # Reverse list to read first user given exception before
168
                 # the hapic default Exception catch
181
                 # the hapic default Exception catch
169
-                handled = reversed(
182
+                handled_exceptions = reversed(
170
                     self._get_handled_exception_class_and_http_codes(),
183
                     self._get_handled_exception_class_and_http_codes(),
171
                 )
184
                 )
172
-                for handled_exception_class, http_code in handled:
185
+                for handled_exception in handled_exceptions:
173
                     # TODO BS 2018-05-04: How to be attentive to hierarchy ?
186
                     # TODO BS 2018-05-04: How to be attentive to hierarchy ?
174
-                    if isinstance(exc, handled_exception_class):
187
+                    if isinstance(exc, handled_exception.exception_class):
175
                         error_builder = self.get_default_error_builder()
188
                         error_builder = self.get_default_error_builder()
176
                         error_body = error_builder.build_from_exception(exc)
189
                         error_body = error_builder.build_from_exception(exc)
177
                         return self.get_response(
190
                         return self.get_response(
178
                             json.dumps(error_body),
191
                             json.dumps(error_body),
179
-                            http_code,
192
+                            handled_exception.http_code,
180
                         )
193
                         )
181
                 raise exc
194
                 raise exc
182
 
195
 
184
 
197
 
185
     def _get_handled_exception_class_and_http_codes(
198
     def _get_handled_exception_class_and_http_codes(
186
         self,
199
         self,
187
-    ) -> typing.List[typing.Tuple[typing.Type[Exception], int]]:
200
+    ) -> typing.List[HandledException]:
188
         """
201
         """
189
         :return: A list of tuple where: thirst item of tuple is a exception
202
         :return: A list of tuple where: thirst item of tuple is a exception
190
         class and second tuple item is a http code. This list will be used by
203
         class and second tuple item is a http code. This list will be used by

+ 6 - 5
hapic/ext/bottle/context.py View File

12
 from multidict import MultiDict
12
 from multidict import MultiDict
13
 
13
 
14
 from hapic.context import BaseContext
14
 from hapic.context import BaseContext
15
+from hapic.context import HandledException
15
 from hapic.context import RouteRepresentation
16
 from hapic.context import RouteRepresentation
16
 from hapic.decorator import DecoratedController
17
 from hapic.decorator import DecoratedController
17
 from hapic.decorator import DECORATION_ATTRIBUTE_NAME
18
 from hapic.decorator import DECORATION_ATTRIBUTE_NAME
33
         app: bottle.Bottle,
34
         app: bottle.Bottle,
34
         default_error_builder: ErrorBuilderInterface=None,
35
         default_error_builder: ErrorBuilderInterface=None,
35
     ):
36
     ):
36
-        self._handled_exception_and_http_codes = []  # type: typing.List[typing.Tuple[typing.Type[Exception], int]]  # nopep8
37
+        self._handled_exceptions = []  # type: typing.List[HandledException]  # nopep8
37
         self._exceptions_handler_installed = False
38
         self._exceptions_handler_installed = False
38
         self.app = app
39
         self.app = app
39
         self.default_error_builder = \
40
         self.default_error_builder = \
145
         if not self._exceptions_handler_installed:
146
         if not self._exceptions_handler_installed:
146
             self._install_exceptions_handler()
147
             self._install_exceptions_handler()
147
 
148
 
148
-        self._handled_exception_and_http_codes.append(
149
-            (exception_class, http_code),
149
+        self._handled_exceptions.append(
150
+            HandledException(exception_class, http_code),
150
         )
151
         )
151
 
152
 
152
     def _install_exceptions_handler(self) -> None:
153
     def _install_exceptions_handler(self) -> None:
154
 
155
 
155
     def _get_handled_exception_class_and_http_codes(
156
     def _get_handled_exception_class_and_http_codes(
156
         self,
157
         self,
157
-    ) -> typing.List[typing.Tuple[typing.Type[Exception], int]]:
158
+    ) -> typing.List[HandledException]:
158
         """
159
         """
159
         See hapic.context.BaseContext#_get_handled_exception_class_and_http_codes  # nopep8
160
         See hapic.context.BaseContext#_get_handled_exception_class_and_http_codes  # nopep8
160
         """
161
         """
161
-        return self._handled_exception_and_http_codes
162
+        return self._handled_exceptions

+ 2 - 5
hapic/ext/flask/context.py View File

33
         app: Flask,
33
         app: Flask,
34
         default_error_builder: ErrorBuilderInterface=None,
34
         default_error_builder: ErrorBuilderInterface=None,
35
     ):
35
     ):
36
-        self._handled_exception_and_http_codes = []  # type: typing.List[typing.Tuple[typing.Type[Exception], int]]  # nopep8
36
+        self._handled_exceptions = []  # type: typing.List[HandledException]  # nopep8
37
         self.app = app
37
         self.app = app
38
         self.default_error_builder = \
38
         self.default_error_builder = \
39
             default_error_builder or DefaultErrorBuilder()  # FDV
39
             default_error_builder or DefaultErrorBuilder()  # FDV
164
         exception_class: typing.Type[Exception],
164
         exception_class: typing.Type[Exception],
165
         http_code: int,
165
         http_code: int,
166
     ) -> None:
166
     ) -> None:
167
-        self._handled_exception_and_http_codes.append(
168
-            (exception_class, http_code),
169
-        )
170
-
167
+        raise NotImplementedError('TODO')

+ 2 - 4
hapic/ext/pyramid/context.py View File

32
         configurator: 'Configurator',
32
         configurator: 'Configurator',
33
         default_error_builder: ErrorBuilderInterface = None,
33
         default_error_builder: ErrorBuilderInterface = None,
34
     ):
34
     ):
35
-        self._handled_exception_and_http_codes = []  # type: typing.List[typing.Tuple[typing.Type[Exception], int]]  # nopep8
35
+        self._handled_exceptions = []  # type: typing.List[HandledException]  # nopep8
36
         self.configurator = configurator
36
         self.configurator = configurator
37
         self.default_error_builder = \
37
         self.default_error_builder = \
38
             default_error_builder or DefaultErrorBuilder()  # FDV
38
             default_error_builder or DefaultErrorBuilder()  # FDV
188
         exception_class: typing.Type[Exception],
188
         exception_class: typing.Type[Exception],
189
         http_code: int,
189
         http_code: int,
190
     ) -> None:
190
     ) -> None:
191
-        self._handled_exception_and_http_codes.append(
192
-            (exception_class, http_code),
193
-        )
191
+        raise NotImplementedError('TODO')

+ 8 - 6
tests/base.py View File

1
 # -*- coding: utf-8 -*-
1
 # -*- coding: utf-8 -*-
2
 import json
2
 import json
3
 import typing
3
 import typing
4
+
5
+
4
 try:  # Python 3.5+
6
 try:  # Python 3.5+
5
     from http import HTTPStatus
7
     from http import HTTPStatus
6
 except ImportError:
8
 except ImportError:
7
     from http import client as HTTPStatus
9
     from http import client as HTTPStatus
8
 
10
 
9
 from multidict import MultiDict
11
 from multidict import MultiDict
10
-import bottle
11
 
12
 
12
 from hapic.ext.bottle import BottleContext
13
 from hapic.ext.bottle import BottleContext
13
 from hapic.processor import RequestParameters
14
 from hapic.processor import RequestParameters
14
 from hapic.processor import ProcessValidationError
15
 from hapic.processor import ProcessValidationError
16
+from hapic.context import HandledException
15
 
17
 
16
 
18
 
17
 class Base(object):
19
 class Base(object):
31
         fake_files_parameters=None,
33
         fake_files_parameters=None,
32
     ) -> None:
34
     ) -> None:
33
         super().__init__(app=app)
35
         super().__init__(app=app)
34
-        self._handled_exception_and_http_codes = []  # type: typing.List[typing.Tuple[typing.Type[Exception], int]]  # nopep8
36
+        self._handled_exceptions = []  # type: typing.List[HandledException]  # nopep8
35
         self._exceptions_handler_installed = False
37
         self._exceptions_handler_installed = False
36
         self.fake_path_parameters = fake_path_parameters or {}
38
         self.fake_path_parameters = fake_path_parameters or {}
37
         self.fake_query_parameters = fake_query_parameters or MultiDict()
39
         self.fake_query_parameters = fake_query_parameters or MultiDict()
73
     ) -> None:
75
     ) -> None:
74
         if not self._exceptions_handler_installed:
76
         if not self._exceptions_handler_installed:
75
             self._install_exceptions_handler()
77
             self._install_exceptions_handler()
76
-        self._handled_exception_and_http_codes.append(
77
-            (exception_class, http_code),
78
+        self._handled_exceptions.append(
79
+            HandledException(exception_class, http_code),
78
         )
80
         )
79
 
81
 
80
     def _get_handled_exception_class_and_http_codes(
82
     def _get_handled_exception_class_and_http_codes(
81
         self,
83
         self,
82
-    ) -> typing.List[typing.Tuple[typing.Type[Exception], int]]:
83
-        return self._handled_exception_and_http_codes
84
+    ) -> typing.List[HandledException]:
85
+        return self._handled_exceptions