| 1 |
""" |
| 2 |
The Request class is used as a wrapper around the standard request object. |
| 3 |
|
| 4 |
The wrapped request then offers a richer API, in particular : |
| 5 |
|
| 6 |
- content automatically parsed according to `Content-Type` header, |
| 7 |
and available as `request.data` |
| 8 |
- full support of PUT method, including support for file uploads |
| 9 |
- form overloading of HTTP method, content type and content |
| 10 |
""" |
| 11 |
import io |
| 12 |
import sys |
| 13 |
from contextlib import contextmanager |
| 14 |
|
| 15 |
from django.conf import settings |
| 16 |
from django.http import HttpRequest, QueryDict |
| 17 |
from django.http.request import RawPostDataException |
| 18 |
from django.utils.datastructures import MultiValueDict |
| 19 |
from django.utils.http import parse_header_parameters |
| 20 |
|
| 21 |
from rest_framework import exceptions |
| 22 |
from rest_framework.settings import api_settings |
| 23 |
|
| 24 |
|
| 25 |
def is_form_media_type(media_type): |
| 26 |
""" |
| 27 |
Return True if the media type is a valid form media type. |
| 28 |
""" |
| 29 |
base_media_type, params = parse_header_parameters(media_type) |
| 30 |
return (base_media_type == 'application/x-www-form-urlencoded' or |
| 31 |
base_media_type == 'multipart/form-data') |
| 32 |
|
| 33 |
|
| 34 |
class override_method: |
| 35 |
""" |
| 36 |
A context manager that temporarily overrides the method on a request, |
| 37 |
additionally setting the `view.request` attribute. |
| 38 |
|
| 39 |
Usage: |
| 40 |
|
| 41 |
with override_method(view, request, 'POST') as request: |
| 42 |
... # Do stuff with `view` and `request` |
| 43 |
""" |
| 44 |
|
| 45 |
def __init__(self, view, request, method): |
| 46 |
self.view = view |
| 47 |
self.request = request |
| 48 |
self.method = method |
| 49 |
self.action = getattr(view, 'action', None) |
| 50 |
|
| 51 |
def __enter__(self): |
| 52 |
self.view.request = clone_request(self.request, self.method) |
| 53 |
# For viewsets we also set the `.action` attribute. |
| 54 |
action_map = getattr(self.view, 'action_map', {}) |
| 55 |
self.view.action = action_map.get(self.method.lower()) |
| 56 |
return self.view.request |
| 57 |
|
| 58 |
def __exit__(self, *args, **kwarg): |
| 59 |
self.view.request = self.request |
| 60 |
self.view.action = self.action |
| 61 |
|
| 62 |
|
| 63 |
class WrappedAttributeError(Exception): |
| 64 |
pass |
| 65 |
|
| 66 |
|
| 67 |
@contextmanager |
| 68 |
def wrap_attributeerrors(): |
| 69 |
""" |
| 70 |
Used to re-raise AttributeErrors caught during authentication, preventing |
| 71 |
these errors from otherwise being handled by the attribute access protocol. |
| 72 |
""" |
| 73 |
try: |
| 74 |
yield |
| 75 |
except AttributeError: |
| 76 |
info = sys.exc_info() |
| 77 |
exc = WrappedAttributeError(str(info[1])) |
| 78 |
raise exc.with_traceback(info[2]) |
| 79 |
|
| 80 |
|
| 81 |
class Empty: |
| 82 |
""" |
| 83 |
Placeholder for unset attributes. |
| 84 |
Cannot use `None`, as that may be a valid value. |
| 85 |
""" |
| 86 |
pass |
| 87 |
|
| 88 |
|
| 89 |
def _hasattr(obj, name): |
| 90 |
return not getattr(obj, name) is Empty |
| 91 |
|
| 92 |
|
| 93 |
def clone_request(request, method): |
| 94 |
""" |
| 95 |
Internal helper method to clone a request, replacing with a different |
| 96 |
HTTP method. Used for checking permissions against other methods. |
| 97 |
""" |
| 98 |
ret = Request(request=request._request, |
| 99 |
parsers=request.parsers, |
| 100 |
authenticators=request.authenticators, |
| 101 |
negotiator=request.negotiator, |
| 102 |
parser_context=request.parser_context) |
| 103 |
ret._data = request._data |
| 104 |
ret._files = request._files |
| 105 |
ret._full_data = request._full_data |
| 106 |
ret._content_type = request._content_type |
| 107 |
ret._stream = request._stream |
| 108 |
ret.method = method |
| 109 |
if hasattr(request, '_user'): |
| 110 |
ret._user = request._user |
| 111 |
if hasattr(request, '_auth'): |
| 112 |
ret._auth = request._auth |
| 113 |
if hasattr(request, '_authenticator'): |
| 114 |
ret._authenticator = request._authenticator |
| 115 |
if hasattr(request, 'accepted_renderer'): |
| 116 |
ret.accepted_renderer = request.accepted_renderer |
| 117 |
if hasattr(request, 'accepted_media_type'): |
| 118 |
ret.accepted_media_type = request.accepted_media_type |
| 119 |
if hasattr(request, 'version'): |
| 120 |
ret.version = request.version |
| 121 |
if hasattr(request, 'versioning_scheme'): |
| 122 |
ret.versioning_scheme = request.versioning_scheme |
| 123 |
return ret |
| 124 |
|
| 125 |
|
| 126 |
class ForcedAuthentication: |
| 127 |
""" |
| 128 |
This authentication class is used if the test client or request factory |
| 129 |
forcibly authenticated the request. |
| 130 |
""" |
| 131 |
|
| 132 |
def __init__(self, force_user, force_token): |
| 133 |
self.force_user = force_user |
| 134 |
self.force_token = force_token |
| 135 |
|
| 136 |
def authenticate(self, request): |
| 137 |
return (self.force_user, self.force_token) |
| 138 |
|
| 139 |
|
| 140 |
class Request: |
| 141 |
""" |
| 142 |
Wrapper allowing to enhance a standard `HttpRequest` instance. |
| 143 |
|
| 144 |
Kwargs: |
| 145 |
- request(HttpRequest). The original request instance. |
| 146 |
- parsers(list/tuple). The parsers to use for parsing the |
| 147 |
request content. |
| 148 |
- authenticators(list/tuple). The authenticators used to try |
| 149 |
authenticating the request's user. |
| 150 |
""" |
| 151 |
|
| 152 |
def __init__(self, request, parsers=None, authenticators=None, |
| 153 |
negotiator=None, parser_context=None): |
| 154 |
assert isinstance(request, HttpRequest), ( |
| 155 |
'The `request` argument must be an instance of ' |
| 156 |
'`django.http.HttpRequest`, not `{}.{}`.' |
| 157 |
.format(request.__class__.__module__, request.__class__.__name__) |
| 158 |
) |
| 159 |
|
| 160 |
self._request = request |
| 161 |
self.parsers = parsers or () |
| 162 |
self.authenticators = authenticators or () |
| 163 |
self.negotiator = negotiator or self._default_negotiator() |
| 164 |
self.parser_context = parser_context |
| 165 |
self._data = Empty |
| 166 |
self._files = Empty |
| 167 |
self._full_data = Empty |
| 168 |
self._content_type = Empty |
| 169 |
self._stream = Empty |
| 170 |
|
| 171 |
if self.parser_context is None: |
| 172 |
self.parser_context = {} |
| 173 |
self.parser_context['request'] = self |
| 174 |
self.parser_context['encoding'] = request.encoding or settings.DEFAULT_CHARSET |
| 175 |
|
| 176 |
force_user = getattr(request, '_force_auth_user', None) |
| 177 |
force_token = getattr(request, '_force_auth_token', None) |
| 178 |
if force_user is not None or force_token is not None: |
| 179 |
forced_auth = ForcedAuthentication(force_user, force_token) |
| 180 |
self.authenticators = (forced_auth,) |
| 181 |
|
| 182 |
def __repr__(self): |
| 183 |
return '<%s.%s: %s %r>' % ( |
| 184 |
self.__class__.__module__, |
| 185 |
self.__class__.__name__, |
| 186 |
self.method, |
| 187 |
self.get_full_path()) |
| 188 |
|
| 189 |
# Allow generic typing checking for requests. |
| 190 |
def __class_getitem__(cls, *args, **kwargs): |
| 191 |
return cls |
| 192 |
|
| 193 |
def _default_negotiator(self): |
| 194 |
return api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS() |
| 195 |
|
| 196 |
@property |
| 197 |
def content_type(self): |
| 198 |
meta = self._request.META |
| 199 |
return meta.get('CONTENT_TYPE', meta.get('HTTP_CONTENT_TYPE', '')) |
| 200 |
|
| 201 |
@property |
| 202 |
def stream(self): |
| 203 |
""" |
| 204 |
Returns an object that may be used to stream the request content. |
| 205 |
""" |
| 206 |
if not _hasattr(self, '_stream'): |
| 207 |
self._load_stream() |
| 208 |
return self._stream |
| 209 |
|
| 210 |
@property |
| 211 |
def query_params(self): |
| 212 |
""" |
| 213 |
More semantically correct name for request.GET. |
| 214 |
""" |
| 215 |
return self._request.GET |
| 216 |
|
| 217 |
@property |
| 218 |
def data(self): |
| 219 |
if not _hasattr(self, '_full_data'): |
| 220 |
with wrap_attributeerrors(): |
| 221 |
self._load_data_and_files() |
| 222 |
return self._full_data |
| 223 |
|
| 224 |
@property |
| 225 |
def user(self): |
| 226 |
""" |
| 227 |
Returns the user associated with the current request, as authenticated |
| 228 |
by the authentication classes provided to the request. |
| 229 |
""" |
| 230 |
if not hasattr(self, '_user'): |
| 231 |
with wrap_attributeerrors(): |
| 232 |
self._authenticate() |
| 233 |
return self._user |
| 234 |
|
| 235 |
@user.setter |
| 236 |
def user(self, value): |
| 237 |
""" |
| 238 |
Sets the user on the current request. This is necessary to maintain |
| 239 |
compatibility with django.contrib.auth where the user property is |
| 240 |
set in the login and logout functions. |
| 241 |
|
| 242 |
Note that we also set the user on Django's underlying `HttpRequest` |
| 243 |
instance, ensuring that it is available to any middleware in the stack. |
| 244 |
""" |
| 245 |
self._user = value |
| 246 |
self._request.user = value |
| 247 |
|
| 248 |
@property |
| 249 |
def auth(self): |
| 250 |
""" |
| 251 |
Returns any non-user authentication information associated with the |
| 252 |
request, such as an authentication token. |
| 253 |
""" |
| 254 |
if not hasattr(self, '_auth'): |
| 255 |
with wrap_attributeerrors(): |
| 256 |
self._authenticate() |
| 257 |
return self._auth |
| 258 |
|
| 259 |
@auth.setter |
| 260 |
def auth(self, value): |
| 261 |
""" |
| 262 |
Sets any non-user authentication information associated with the |
| 263 |
request, such as an authentication token. |
| 264 |
""" |
| 265 |
self._auth = value |
| 266 |
self._request.auth = value |
| 267 |
|
| 268 |
@property |
| 269 |
def successful_authenticator(self): |
| 270 |
""" |
| 271 |
Return the instance of the authentication instance class that was used |
| 272 |
to authenticate the request, or `None`. |
| 273 |
""" |
| 274 |
if not hasattr(self, '_authenticator'): |
| 275 |
with wrap_attributeerrors(): |
| 276 |
self._authenticate() |
| 277 |
return self._authenticator |
| 278 |
|
| 279 |
def _load_data_and_files(self): |
| 280 |
""" |
| 281 |
Parses the request content into `self.data`. |
| 282 |
""" |
| 283 |
if not _hasattr(self, '_data'): |
| 284 |
self._data, self._files = self._parse() |
| 285 |
if self._files: |
| 286 |
self._full_data = self._data.copy() |
| 287 |
self._full_data.update(self._files) |
| 288 |
else: |
| 289 |
self._full_data = self._data |
| 290 |
|
| 291 |
# if a form media type, copy data & files refs to the underlying |
| 292 |
# http request so that closable objects are handled appropriately. |
| 293 |
if is_form_media_type(self.content_type): |
| 294 |
self._request._post = self.POST |
| 295 |
self._request._files = self.FILES |
| 296 |
|
| 297 |
def _load_stream(self): |
| 298 |
""" |
| 299 |
Return the content body of the request, as a stream. |
| 300 |
""" |
| 301 |
meta = self._request.META |
| 302 |
try: |
| 303 |
content_length = int( |
| 304 |
meta.get('CONTENT_LENGTH', meta.get('HTTP_CONTENT_LENGTH', 0)) |
| 305 |
) |
| 306 |
except (ValueError, TypeError): |
| 307 |
content_length = 0 |
| 308 |
|
| 309 |
if content_length == 0: |
| 310 |
self._stream = None |
| 311 |
elif not self._request._read_started: |
| 312 |
self._stream = self._request |
| 313 |
else: |
| 314 |
self._stream = io.BytesIO(self.body) |
| 315 |
|
| 316 |
def _supports_form_parsing(self): |
| 317 |
""" |
| 318 |
Return True if this requests supports parsing form data. |
| 319 |
""" |
| 320 |
form_media = ( |
| 321 |
'application/x-www-form-urlencoded', |
| 322 |
'multipart/form-data' |
| 323 |
) |
| 324 |
return any(parser.media_type in form_media for parser in self.parsers) |
| 325 |
|
| 326 |
def _parse(self): |
| 327 |
""" |
| 328 |
Parse the request content, returning a two-tuple of (data, files) |
| 329 |
|
| 330 |
May raise an `UnsupportedMediaType`, or `ParseError` exception. |
| 331 |
""" |
| 332 |
media_type = self.content_type |
| 333 |
try: |
| 334 |
stream = self.stream |
| 335 |
except RawPostDataException: |
| 336 |
if not hasattr(self._request, '_post'): |
| 337 |
raise |
| 338 |
# If request.POST has been accessed in middleware, and a method='POST' |
| 339 |
# request was made with 'multipart/form-data', then the request stream |
| 340 |
# will already have been exhausted. |
| 341 |
if self._supports_form_parsing(): |
| 342 |
return (self._request.POST, self._request.FILES) |
| 343 |
stream = None |
| 344 |
|
| 345 |
if stream is None or media_type is None: |
| 346 |
if media_type and is_form_media_type(media_type): |
| 347 |
empty_data = QueryDict('', encoding=self._request._encoding) |
| 348 |
else: |
| 349 |
empty_data = {} |
| 350 |
empty_files = MultiValueDict() |
| 351 |
return (empty_data, empty_files) |
| 352 |
|
| 353 |
parser = self.negotiator.select_parser(self, self.parsers) |
| 354 |
|
| 355 |
if not parser: |
| 356 |
raise exceptions.UnsupportedMediaType(media_type) |
| 357 |
|
| 358 |
from rest_framework.parsers import FormParser, JSONParser |
| 359 |
if isinstance(parser, (JSONParser, FormParser)): |
| 360 |
stream = io.BytesIO(self.body) |
| 361 |
|
| 362 |
try: |
| 363 |
parsed = parser.parse(stream, media_type, self.parser_context) |
| 364 |
except Exception: |
| 365 |
# If we get an exception during parsing, fill in empty data and |
| 366 |
# re-raise. Ensures we don't simply repeat the error when |
| 367 |
# attempting to render the browsable renderer response, or when |
| 368 |
# logging the request or similar. |
| 369 |
self._data = QueryDict('', encoding=self._request._encoding) |
| 370 |
self._files = MultiValueDict() |
| 371 |
self._full_data = self._data |
| 372 |
raise |
| 373 |
|
| 374 |
# Parser classes may return the raw data, or a |
| 375 |
# DataAndFiles object. Unpack the result as required. |
| 376 |
try: |
| 377 |
return (parsed.data, parsed.files) |
| 378 |
except AttributeError: |
| 379 |
empty_files = MultiValueDict() |
| 380 |
return (parsed, empty_files) |
| 381 |
|
| 382 |
def _authenticate(self): |
| 383 |
""" |
| 384 |
Attempt to authenticate the request using each authentication instance |
| 385 |
in turn. |
| 386 |
""" |
| 387 |
for authenticator in self.authenticators: |
| 388 |
try: |
| 389 |
user_auth_tuple = authenticator.authenticate(self) |
| 390 |
except exceptions.APIException: |
| 391 |
self._not_authenticated() |
| 392 |
raise |
| 393 |
|
| 394 |
if user_auth_tuple is not None: |
| 395 |
self._authenticator = authenticator |
| 396 |
self.user, self.auth = user_auth_tuple |
| 397 |
return |
| 398 |
|
| 399 |
self._not_authenticated() |
| 400 |
|
| 401 |
def _not_authenticated(self): |
| 402 |
""" |
| 403 |
Set authenticator, user & authtoken representing an unauthenticated request. |
| 404 |
|
| 405 |
Defaults are None, AnonymousUser & None. |
| 406 |
""" |
| 407 |
self._authenticator = None |
| 408 |
|
| 409 |
if api_settings.UNAUTHENTICATED_USER: |
| 410 |
self.user = api_settings.UNAUTHENTICATED_USER() |
| 411 |
else: |
| 412 |
self.user = None |
| 413 |
|
| 414 |
if api_settings.UNAUTHENTICATED_TOKEN: |
| 415 |
self.auth = api_settings.UNAUTHENTICATED_TOKEN() |
| 416 |
else: |
| 417 |
self.auth = None |
| 418 |
|
| 419 |
def __getattr__(self, attr): |
| 420 |
""" |
| 421 |
If an attribute does not exist on this instance, then we also attempt |
| 422 |
to proxy it to the underlying HttpRequest object. |
| 423 |
""" |
| 424 |
try: |
| 425 |
_request = self.__getattribute__("_request") |
| 426 |
return getattr(_request, attr) |
| 427 |
except AttributeError: |
| 428 |
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attr}'") |
| 429 |
|
| 430 |
@property |
| 431 |
def POST(self): |
| 432 |
# Ensure that request.POST uses our request parsing. |
| 433 |
if not _hasattr(self, '_data'): |
| 434 |
with wrap_attributeerrors(): |
| 435 |
self._load_data_and_files() |
| 436 |
if is_form_media_type(self.content_type): |
| 437 |
return self._data |
| 438 |
return QueryDict('', encoding=self._request._encoding) |
| 439 |
|
| 440 |
@property |
| 441 |
def FILES(self): |
| 442 |
# Leave this one alone for backwards compat with Django's request.FILES |
| 443 |
# Different from the other two cases, which are not valid property |
| 444 |
# names on the WSGIRequest class. |
| 445 |
if not _hasattr(self, '_files'): |
| 446 |
with wrap_attributeerrors(): |
| 447 |
self._load_data_and_files() |
| 448 |
return self._files |
| 449 |
|
| 450 |
def force_plaintext_errors(self, value): |
| 451 |
# Hack to allow our exception handler to force choice of |
| 452 |
# plaintext or html error responses. |
| 453 |
self._request.is_ajax = lambda: value |