|
| 1 | +from django.http import Http404 |
| 2 | +from django.core.exceptions import ValidationError |
| 3 | + |
| 4 | + |
| 5 | +class APIReqHandler: |
| 6 | + """ |
| 7 | + The APIReqHandler class provides a wrapper that adds |
| 8 | + a message parameter to a function that returns a dictionary. |
| 9 | + Combine with the jsonate_response decorator to use with |
| 10 | + clients expecting json. |
| 11 | +
|
| 12 | + If the view raised no errors, the message content is 'ok'. |
| 13 | + Http404 and validation errors return the error message to the client, |
| 14 | + all other exceptions are raised. |
| 15 | +
|
| 16 | + Example: |
| 17 | + @jsonate_response |
| 18 | + def my_view(request, some_arg) |
| 19 | + return APIReqHandler(my_func).handle(some_arg) |
| 20 | +
|
| 21 | + Parameters: |
| 22 | + - view_f (function): A function that returns a dictionary. |
| 23 | + - resp_ok (function, optional): A function to execute if no errors are raised. |
| 24 | + - resp_err (function, optional): A function to execute if errors are raised. |
| 25 | +
|
| 26 | + Methods: |
| 27 | + - handle(*args, **kwargs) -- return the function with added message. |
| 28 | + """ |
| 29 | + def __init__(self, view_f, resp_ok=None, resp_err=None): |
| 30 | + self.view_f = view_f |
| 31 | + self.resp_ok = resp_ok or self._resp_ok |
| 32 | + self.resp_err = resp_err or self._resp_error |
| 33 | + |
| 34 | + @staticmethod |
| 35 | + def _resp_ok(extra): |
| 36 | + extra_data = extra or {} |
| 37 | + return { |
| 38 | + "message": "ok", |
| 39 | + **{k: v for k, v in extra_data.items()} |
| 40 | + } |
| 41 | + |
| 42 | + @staticmethod |
| 43 | + def _resp_error(err): |
| 44 | + return {"message": f"{err.__class__.__name__}: {err}"} |
| 45 | + |
| 46 | + def handle(self, *args, **kwargs): |
| 47 | + try: |
| 48 | + return self.resp_ok(self.view_f(*args, **kwargs)) |
| 49 | + except (Http404, ValidationError) as err: |
| 50 | + return self.resp_err(err) |
| 51 | + except Exception: |
| 52 | + raise |
0 commit comments