Debian Codegraph @

rest_framework/exceptions.py

raw
1 """
2 Handled exceptions raised by REST framework.
3
4 In addition, Django's built in 403 and 404 exceptions are handled.
5 (`django.http.Http404` and `django.core.exceptions.PermissionDenied`)
6 """
7 import math
8
9 from django.http import JsonResponse
10 from django.utils.encoding import force_str
11 from django.utils.translation import gettext_lazy as _
12 from django.utils.translation import ngettext
13
14 from rest_framework import status
15 from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
16
17
18 def _get_error_details(data, default_code=None):
19 """
20 Descend into a nested data structure, forcing any
21 lazy translation strings or strings into `ErrorDetail`.
22 """
23 if isinstance(data, (list, tuple)):
24 ret = [
25 _get_error_details(item, default_code) for item in data
26 ]
27 if isinstance(data, ReturnList):
28 return ReturnList(ret, serializer=data.serializer)
29 return ret
30 elif isinstance(data, dict):
31 ret = {
32 key: _get_error_details(value, default_code)
33 for key, value in data.items()
34 }
35 if isinstance(data, ReturnDict):
36 return ReturnDict(ret, serializer=data.serializer)
37 return ret
38
39 text = force_str(data)
40 code = getattr(data, 'code', default_code)
41 return ErrorDetail(text, code)
42
43
44 def _get_codes(detail):
45 if isinstance(detail, list):
46 return [_get_codes(item) for item in detail]
47 elif isinstance(detail, dict):
48 return {key: _get_codes(value) for key, value in detail.items()}
49 return detail.code
50
51
52 def _get_full_details(detail):
53 if isinstance(detail, list):
54 return [_get_full_details(item) for item in detail]
55 elif isinstance(detail, dict):
56 return {key: _get_full_details(value) for key, value in detail.items()}
57 return {
58 'message': detail,
59 'code': detail.code
60 }
61
62
63 class ErrorDetail(str):
64 """
65 A string-like object that can additionally have a code.
66 """
67 code = None
68
69 def __new__(cls, string, code=None):
70 self = super().__new__(cls, string)
71 self.code = code
72 return self
73
74 def __eq__(self, other):
75 result = super().__eq__(other)
76 if result is NotImplemented:
77 return NotImplemented
78 try:
79 return result and self.code == other.code
80 except AttributeError:
81 return result
82
83 def __ne__(self, other):
84 result = self.__eq__(other)
85 if result is NotImplemented:
86 return NotImplemented
87 return not result
88
89 def __repr__(self):
90 return 'ErrorDetail(string=%r, code=%r)' % (
91 str(self),
92 self.code,
93 )
94
95 def __hash__(self):
96 return hash(str(self))
97
98
99 class APIException(Exception):
100 """
101 Base class for REST framework exceptions.
102 Subclasses should provide `.status_code` and `.default_detail` properties.
103 """
104 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
105 default_detail = _('A server error occurred.')
106 default_code = 'error'
107
108 def __init__(self, detail=None, code=None):
109 if detail is None:
110 detail = self.default_detail
111 if code is None:
112 code = self.default_code
113
114 self.detail = _get_error_details(detail, code)
115
116 def __str__(self):
117 return str(self.detail)
118
119 def get_codes(self):
120 """
121 Return only the code part of the error details.
122
123 Eg. {"name": ["required"]}
124 """
125 return _get_codes(self.detail)
126
127 def get_full_details(self):
128 """
129 Return both the message & code parts of the error details.
130
131 Eg. {"name": [{"message": "This field is required.", "code": "required"}]}
132 """
133 return _get_full_details(self.detail)
134
135
136 # The recommended style for using `ValidationError` is to keep it namespaced
137 # under `serializers`, in order to minimize potential confusion with Django's
138 # built in `ValidationError`. For example:
139 #
140 # from rest_framework import serializers
141 # raise serializers.ValidationError('Value was invalid')
142
143 class ValidationError(APIException):
144 status_code = status.HTTP_400_BAD_REQUEST
145 default_detail = _('Invalid input.')
146 default_code = 'invalid'
147
148 def __init__(self, detail=None, code=None):
149 if detail is None:
150 detail = self.default_detail
151 if code is None:
152 code = self.default_code
153
154 # For validation failures, we may collect many errors together,
155 # so the details should always be coerced to a list if not already.
156 if isinstance(detail, tuple):
157 detail = list(detail)
158 elif not isinstance(detail, dict) and not isinstance(detail, list):
159 detail = [detail]
160
161 self.detail = _get_error_details(detail, code)
162
163
164 class ParseError(APIException):
165 status_code = status.HTTP_400_BAD_REQUEST
166 default_detail = _('Malformed request.')
167 default_code = 'parse_error'
168
169
170 class AuthenticationFailed(APIException):
171 status_code = status.HTTP_401_UNAUTHORIZED
172 default_detail = _('Incorrect authentication credentials.')
173 default_code = 'authentication_failed'
174
175
176 class NotAuthenticated(APIException):
177 status_code = status.HTTP_401_UNAUTHORIZED
178 default_detail = _('Authentication credentials were not provided.')
179 default_code = 'not_authenticated'
180
181
182 class PermissionDenied(APIException):
183 status_code = status.HTTP_403_FORBIDDEN
184 default_detail = _('You do not have permission to perform this action.')
185 default_code = 'permission_denied'
186
187
188 class NotFound(APIException):
189 status_code = status.HTTP_404_NOT_FOUND
190 default_detail = _('Not found.')
191 default_code = 'not_found'
192
193
194 class MethodNotAllowed(APIException):
195 status_code = status.HTTP_405_METHOD_NOT_ALLOWED
196 default_detail = _('Method "{method}" not allowed.')
197 default_code = 'method_not_allowed'
198
199 def __init__(self, method, detail=None, code=None):
200 if detail is None:
201 detail = force_str(self.default_detail).format(method=method)
202 super().__init__(detail, code)
203
204
205 class NotAcceptable(APIException):
206 status_code = status.HTTP_406_NOT_ACCEPTABLE
207 default_detail = _('Could not satisfy the request Accept header.')
208 default_code = 'not_acceptable'
209
210 def __init__(self, detail=None, code=None, available_renderers=None):
211 self.available_renderers = available_renderers
212 super().__init__(detail, code)
213
214
215 class UnsupportedMediaType(APIException):
216 status_code = status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
217 default_detail = _('Unsupported media type "{media_type}" in request.')
218 default_code = 'unsupported_media_type'
219
220 def __init__(self, media_type, detail=None, code=None):
221 if detail is None:
222 detail = force_str(self.default_detail).format(media_type=media_type)
223 super().__init__(detail, code)
224
225
226 class Throttled(APIException):
227 status_code = status.HTTP_429_TOO_MANY_REQUESTS
228 default_detail = _('Request was throttled.')
229 extra_detail_singular = _('Expected available in {wait} second.')
230 extra_detail_plural = _('Expected available in {wait} seconds.')
231 default_code = 'throttled'
232
233 def __init__(self, wait=None, detail=None, code=None):
234 if detail is None:
235 detail = force_str(self.default_detail)
236 if wait is not None:
237 wait = math.ceil(wait)
238 detail = ' '.join((
239 detail,
240 force_str(ngettext(self.extra_detail_singular.format(wait=wait),
241 self.extra_detail_plural.format(wait=wait),
242 wait))))
243 self.wait = wait
244 super().__init__(detail, code)
245
246
247 def server_error(request, *args, **kwargs):
248 """
249 Generic 500 error handler.
250 """
251 data = {
252 'error': 'Server Error (500)'
253 }
254 return JsonResponse(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
255
256
257 def bad_request(request, exception, *args, **kwargs):
258 """
259 Generic 400 error handler.
260 """
261 data = {
262 'error': 'Bad Request (400)'
263 }
264 return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST)