| 1 |
import logging |
| 2 |
import traceback |
| 3 |
from functools import partial |
| 4 |
from typing import TYPE_CHECKING, Generic, List, Optional, TypeVar |
| 5 |
|
| 6 |
import pydantic |
| 7 |
from django.conf import settings |
| 8 |
from django.http import Http404, HttpRequest, HttpResponse |
| 9 |
|
| 10 |
from ninja.types import DictStrAny |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from ninja import NinjaAPI |
| 14 |
from ninja.params.models import ParamModel |
| 15 |
|
| 16 |
__all__ = [ |
| 17 |
"ConfigError", |
| 18 |
"AuthenticationError", |
| 19 |
"AuthorizationError", |
| 20 |
"ValidationError", |
| 21 |
"HttpError", |
| 22 |
"set_default_exc_handlers", |
| 23 |
] |
| 24 |
|
| 25 |
|
| 26 |
logger = logging.getLogger("django") |
| 27 |
|
| 28 |
|
| 29 |
class ConfigError(Exception): |
| 30 |
pass |
| 31 |
|
| 32 |
|
| 33 |
TModel = TypeVar("TModel", bound="ParamModel") |
| 34 |
|
| 35 |
|
| 36 |
class ValidationErrorContext(Generic[TModel]): |
| 37 |
""" |
| 38 |
The full context of a `pydantic.ValidationError`, including all information |
| 39 |
needed to produce a `ninja.errors.ValidationError`. |
| 40 |
""" |
| 41 |
|
| 42 |
def __init__( |
| 43 |
self, pydantic_validation_error: pydantic.ValidationError, model: TModel |
| 44 |
): |
| 45 |
self.pydantic_validation_error = pydantic_validation_error |
| 46 |
self.model = model |
| 47 |
|
| 48 |
|
| 49 |
class ValidationError(Exception): |
| 50 |
""" |
| 51 |
This exception raised when operation params do not validate |
| 52 |
Note: this is not the same as pydantic.ValidationError |
| 53 |
the errors attribute as well holds the location of the error(body, form, query, etc.) |
| 54 |
""" |
| 55 |
|
| 56 |
def __init__(self, errors: List[DictStrAny]) -> None: |
| 57 |
self.errors = errors |
| 58 |
super().__init__(errors) |
| 59 |
|
| 60 |
|
| 61 |
class HttpError(Exception): |
| 62 |
def __init__(self, status_code: int, message: str) -> None: |
| 63 |
self.status_code = status_code |
| 64 |
self.message = message |
| 65 |
super().__init__(status_code, message) |
| 66 |
|
| 67 |
def __str__(self) -> str: |
| 68 |
return self.message |
| 69 |
|
| 70 |
|
| 71 |
class AuthenticationError(HttpError): |
| 72 |
def __init__(self, status_code: int = 401, message: str = "Unauthorized") -> None: |
| 73 |
super().__init__(status_code=status_code, message=message) |
| 74 |
|
| 75 |
|
| 76 |
class AuthorizationError(HttpError): |
| 77 |
def __init__(self, status_code: int = 403, message: str = "Forbidden") -> None: |
| 78 |
super().__init__(status_code=status_code, message=message) |
| 79 |
|
| 80 |
|
| 81 |
class Throttled(HttpError): |
| 82 |
def __init__(self, wait: Optional[int]) -> None: |
| 83 |
self.wait = wait |
| 84 |
super().__init__(status_code=429, message="Too many requests.") |
| 85 |
|
| 86 |
|
| 87 |
def set_default_exc_handlers(api: "NinjaAPI") -> None: |
| 88 |
api.add_exception_handler( |
| 89 |
Exception, |
| 90 |
partial(_default_exception, api=api), |
| 91 |
) |
| 92 |
api.add_exception_handler( |
| 93 |
Http404, |
| 94 |
partial(_default_404, api=api), |
| 95 |
) |
| 96 |
api.add_exception_handler( |
| 97 |
HttpError, |
| 98 |
partial(_default_http_error, api=api), |
| 99 |
) |
| 100 |
api.add_exception_handler( |
| 101 |
ValidationError, |
| 102 |
partial(_default_validation_error, api=api), |
| 103 |
) |
| 104 |
|
| 105 |
|
| 106 |
def _default_404(request: HttpRequest, exc: Exception, api: "NinjaAPI") -> HttpResponse: |
| 107 |
msg = "Not Found" |
| 108 |
if settings.DEBUG: |
| 109 |
msg += f": {exc}" |
| 110 |
return api.create_response(request, {"detail": msg}, status=404) |
| 111 |
|
| 112 |
|
| 113 |
def _default_http_error( |
| 114 |
request: HttpRequest, exc: HttpError, api: "NinjaAPI" |
| 115 |
) -> HttpResponse: |
| 116 |
return api.create_response(request, {"detail": str(exc)}, status=exc.status_code) |
| 117 |
|
| 118 |
|
| 119 |
def _default_validation_error( |
| 120 |
request: HttpRequest, exc: ValidationError, api: "NinjaAPI" |
| 121 |
) -> HttpResponse: |
| 122 |
return api.create_response(request, {"detail": exc.errors}, status=422) |
| 123 |
|
| 124 |
|
| 125 |
def _default_exception( |
| 126 |
request: HttpRequest, exc: Exception, api: "NinjaAPI" |
| 127 |
) -> HttpResponse: |
| 128 |
if not settings.DEBUG: |
| 129 |
raise exc |
| 130 |
|
| 131 |
logger.exception(exc) |
| 132 |
tb = traceback.format_exc() |
| 133 |
return HttpResponse(tb, status=500, content_type="text/plain") |