request.py 15 KB

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