Skip to content
This repository was archived by the owner on Nov 19, 2024. It is now read-only.

Commit bc7124d

Browse files
committed
chore: Applied suggestions from coderabbit
1 parent 0105eb3 commit bc7124d

13 files changed

+69
-102
lines changed

flask_utils/decorators.py

Lines changed: 35 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from typing import get_origin
99
from functools import wraps
1010

11+
from flask import Response
1112
from flask import jsonify
1213
from flask import request
1314
from flask import current_app
@@ -20,6 +21,20 @@
2021
VALIDATE_PARAMS_MAX_DEPTH = 4
2122

2223

24+
def _handle_bad_request(
25+
use_error_handlers: bool,
26+
message: str,
27+
solution: Optional[str] = None,
28+
status_code: int = 400,
29+
original_exception: Optional[Exception] = None,
30+
) -> Response:
31+
if use_error_handlers:
32+
raise BadRequestError(message, solution) from original_exception
33+
else:
34+
error_response = {"error": message}
35+
return make_response(jsonify(error_response), status_code)
36+
37+
2338
def _is_optional(type_hint: Type) -> bool: # type: ignore
2439
"""Check if the type hint is :data:`~typing.Optional`.
2540
@@ -246,115 +261,45 @@ def example():
246261
def decorator(fn): # type: ignore
247262
@wraps(fn)
248263
def wrapper(*args, **kwargs): # type: ignore
249-
use_error_handlers = False
250-
if current_app.extensions.get("flask_utils") is not None:
251-
if current_app.extensions["flask_utils"].has_error_handlers_registered:
252-
use_error_handlers = True
264+
use_error_handlers = (
265+
current_app.extensions.get("flask_utils") is not None
266+
and current_app.extensions["flask_utils"].has_error_handlers_registered
267+
)
253268

254269
try:
255270
data = request.get_json()
256271
except BadRequest as e:
257-
if use_error_handlers:
258-
raise BadRequestError("The Json Body is malformed.") from e
259-
else:
260-
return make_response(
261-
jsonify(
262-
{
263-
"error": "The Json Body is malformed.",
264-
}
265-
),
266-
400,
267-
)
272+
return _handle_bad_request(use_error_handlers, "The Json Body is malformed.", original_exception=e)
268273
except UnsupportedMediaType as e:
269-
if use_error_handlers:
270-
raise BadRequestError(
271-
"The Content-Type header is missing or is not set to application/json, "
272-
"or the JSON body is missing."
273-
) from e
274-
else:
275-
return make_response(
276-
jsonify(
277-
{
278-
"error": "The Content-Type header is missing or is not set to application/json, "
279-
"or the JSON body is missing.",
280-
}
281-
),
282-
400,
283-
)
274+
return _handle_bad_request(
275+
use_error_handlers,
276+
"The Content-Type header is missing or is not set to application/json, "
277+
"or the JSON body is missing.",
278+
original_exception=e,
279+
)
284280

285281
if not data:
286-
if use_error_handlers:
287-
raise BadRequestError("Missing json body.")
288-
else:
289-
return make_response(
290-
jsonify(
291-
{
292-
"error": "Missing json body.",
293-
}
294-
),
295-
400,
296-
)
282+
return _handle_bad_request(use_error_handlers, "Missing json body.")
297283

298284
if not isinstance(data, dict):
299-
if use_error_handlers:
300-
raise BadRequestError("JSON body must be a dict")
301-
else:
302-
return make_response(
303-
jsonify(
304-
{
305-
"error": "JSON body must be a dict",
306-
}
307-
),
308-
400,
309-
)
285+
return _handle_bad_request(use_error_handlers, "JSON body must be a dict")
310286

311287
for key, type_hint in parameters.items():
312288
if not _is_optional(type_hint) and key not in data:
313-
if use_error_handlers:
314-
raise BadRequestError(f"Missing key: {key}", f"Expected keys are: {parameters.keys()}")
315-
else:
316-
return make_response(
317-
jsonify(
318-
{
319-
"error": f"Missing key: {key}",
320-
"expected_keys": parameters.keys(),
321-
}
322-
),
323-
400,
324-
)
289+
return _handle_bad_request(
290+
use_error_handlers, f"Missing key: {key}", f"Expected keys are: {parameters.keys()}"
291+
)
325292

326293
for key in data:
327294
if key not in parameters:
328295
if use_error_handlers:
329-
raise BadRequestError(
330-
f"Unexpected key: {key}.",
331-
f"Expected keys are: {parameters.keys()}",
332-
)
333-
else:
334-
return make_response(
335-
jsonify(
336-
{
337-
"error": f"Unexpected key: {key}.",
338-
"expected_keys": parameters.keys(),
339-
}
340-
),
341-
400,
342-
)
296+
raise BadRequestError(f"Unexpected key: {key}.", f"Expected keys are: {parameters.keys()}")
343297

344298
for key in data:
345299
if key in parameters and not _check_type(data[key], parameters[key], allow_empty):
346-
if use_error_handlers:
347-
raise BadRequestError(f"Wrong type for key {key}.", f"It should be {parameters[key]}")
348-
else:
349-
return make_response(
350-
jsonify(
351-
{
352-
"error": f"Wrong type for key {key}.",
353-
"expected_type": parameters[key],
354-
}
355-
),
356-
400,
357-
)
300+
return _handle_bad_request(
301+
use_error_handlers, f"Wrong type for key {key}.", f"It should be {parameters[key]}"
302+
)
358303

359304
return fn(*args, **kwargs)
360305

flask_utils/errors/badrequest.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from flask_utils.errors.base_class import _BaseFlaskException
24

35

@@ -40,7 +42,7 @@ def example_route():
4042
.. versionadded:: 0.1.0
4143
"""
4244

43-
def __init__(self, msg: str, solution: str = "Try again.") -> None:
45+
def __init__(self, msg: str, solution: Optional[str] = "Try again.") -> None:
4446
self.name = "Bad Request"
4547
self.msg = msg
4648
self.solution = solution

flask_utils/errors/base_class.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44
class _BaseFlaskException(Exception):
55
name: Optional[str] = None
66
msg: Optional[str] = None
7-
solution: str = "Try again."
7+
solution: Optional[str] = "Try again."

flask_utils/errors/conflict.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from flask_utils.errors.base_class import _BaseFlaskException
24

35

@@ -40,7 +42,7 @@ def example_route():
4042
.. versionadded:: 0.1.0
4143
"""
4244

43-
def __init__(self, msg: str, solution: str = "Try again.") -> None:
45+
def __init__(self, msg: str, solution: Optional[str] = "Try again.") -> None:
4446
self.name = "Conflict"
4547
self.msg = msg
4648
self.solution = solution

flask_utils/errors/failed_dependency.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from flask_utils.errors.base_class import _BaseFlaskException
24

35

@@ -40,7 +42,7 @@ def example_route():
4042
.. versionadded:: 0.1.0
4143
"""
4244

43-
def __init__(self, msg: str, solution: str = "Try again later.") -> None:
45+
def __init__(self, msg: str, solution: Optional[str] = "Try again later.") -> None:
4446
self.name = "Failed Dependency"
4547
self.msg = msg
4648
self.solution = solution

flask_utils/errors/forbidden.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from flask_utils.errors.base_class import _BaseFlaskException
24

35

@@ -40,7 +42,7 @@ def example_route():
4042
.. versionadded:: 0.1.0
4143
"""
4244

43-
def __init__(self, msg: str, solution: str = "Try again.") -> None:
45+
def __init__(self, msg: str, solution: Optional[str] = "Try again.") -> None:
4446
self.name = "Forbidden"
4547
self.msg = msg
4648
self.solution = solution

flask_utils/errors/gone.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from flask_utils.errors.base_class import _BaseFlaskException
24

35

@@ -40,7 +42,7 @@ def example_route():
4042
.. versionadded:: 0.1.0
4143
"""
4244

43-
def __init__(self, msg: str, solution: str = "Try again later.") -> None:
45+
def __init__(self, msg: str, solution: Optional[str] = "Try again later.") -> None:
4446
self.name = "Ressource is gone."
4547
self.msg = msg
4648
self.solution = solution

flask_utils/errors/notfound.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from flask_utils.errors.base_class import _BaseFlaskException
24

35

@@ -40,7 +42,7 @@ def example_route():
4042
.. versionadded:: 0.1.0
4143
"""
4244

43-
def __init__(self, msg: str, solution: str = "Try again.") -> None:
45+
def __init__(self, msg: str, solution: Optional[str] = "Try again.") -> None:
4446
self.name = "Not Found"
4547
self.msg = msg
4648
self.solution = solution

flask_utils/errors/origin_is_unreachable.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from flask_utils.errors.base_class import _BaseFlaskException
24

35

@@ -40,7 +42,7 @@ def example_route():
4042
.. versionadded:: 0.1.0
4143
"""
4244

43-
def __init__(self, msg: str, solution: str = "Try again later.") -> None:
45+
def __init__(self, msg: str, solution: Optional[str] = "Try again later.") -> None:
4446
self.name = "Origin is unreachable"
4547
self.msg = msg
4648
self.solution = solution

flask_utils/errors/service_unavailable.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from flask_utils.errors.base_class import _BaseFlaskException
24

35

@@ -40,7 +42,7 @@ def example_route():
4042
.. versionadded:: 0.1.0
4143
"""
4244

43-
def __init__(self, msg: str, solution: str = "Try again later.") -> None:
45+
def __init__(self, msg: str, solution: Optional[str] = "Try again later.") -> None:
4446
self.name = "Service Unavailable"
4547
self.msg = msg
4648
self.solution = solution

0 commit comments

Comments
 (0)