request.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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(list/tuple). The parsers to use for parsing the
  117. request content.
  118. - authenticators(list/tuple). The authenticators 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 __repr__(self):
  148. return '<%s.%s: %s %r>' % (
  149. self.__class__.__module__,
  150. self.__class__.__name__,
  151. self.method,
  152. self.get_full_path())
  153. def _default_negotiator(self):
  154. return api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS()
  155. @property
  156. def content_type(self):
  157. meta = self._request.META
  158. return meta.get('CONTENT_TYPE', meta.get('HTTP_CONTENT_TYPE', ''))
  159. @property
  160. def stream(self):
  161. """
  162. Returns an object that may be used to stream the request content.
  163. """
  164. if not _hasattr(self, '_stream'):
  165. self._load_stream()
  166. return self._stream
  167. @property
  168. def query_params(self):
  169. """
  170. More semantically correct name for request.GET.
  171. """
  172. return self._request.GET
  173. @property
  174. def data(self):
  175. if not _hasattr(self, '_full_data'):
  176. self._load_data_and_files()
  177. return self._full_data
  178. @property
  179. def user(self):
  180. """
  181. Returns the user associated with the current request, as authenticated
  182. by the authentication classes provided to the request.
  183. """
  184. if not hasattr(self, '_user'):
  185. with wrap_attributeerrors():
  186. self._authenticate()
  187. return self._user
  188. @user.setter
  189. def user(self, value):
  190. """
  191. Sets the user on the current request. This is necessary to maintain
  192. compatibility with django.contrib.auth where the user property is
  193. set in the login and logout functions.
  194. Note that we also set the user on Django's underlying `HttpRequest`
  195. instance, ensuring that it is available to any middleware in the stack.
  196. """
  197. self._user = value
  198. self._request.user = value
  199. @property
  200. def auth(self):
  201. """
  202. Returns any non-user authentication information associated with the
  203. request, such as an authentication token.
  204. """
  205. if not hasattr(self, '_auth'):
  206. with wrap_attributeerrors():
  207. self._authenticate()
  208. return self._auth
  209. @auth.setter
  210. def auth(self, value):
  211. """
  212. Sets any non-user authentication information associated with the
  213. request, such as an authentication token.
  214. """
  215. self._auth = value
  216. self._request.auth = value
  217. @property
  218. def successful_authenticator(self):
  219. """
  220. Return the instance of the authentication instance class that was used
  221. to authenticate the request, or `None`.
  222. """
  223. if not hasattr(self, '_authenticator'):
  224. with wrap_attributeerrors():
  225. self._authenticate()
  226. return self._authenticator
  227. def _load_data_and_files(self):
  228. """
  229. Parses the request content into `self.data`.
  230. """
  231. if not _hasattr(self, '_data'):
  232. self._data, self._files = self._parse()
  233. if self._files:
  234. self._full_data = self._data.copy()
  235. self._full_data.update(self._files)
  236. else:
  237. self._full_data = self._data
  238. # if a form media type, copy data & files refs to the underlying
  239. # http request so that closable objects are handled appropriately.
  240. if is_form_media_type(self.content_type):
  241. self._request._post = self.POST
  242. self._request._files = self.FILES
  243. def _load_stream(self):
  244. """
  245. Return the content body of the request, as a stream.
  246. """
  247. meta = self._request.META
  248. try:
  249. content_length = int(
  250. meta.get('CONTENT_LENGTH', meta.get('HTTP_CONTENT_LENGTH', 0))
  251. )
  252. except (ValueError, TypeError):
  253. content_length = 0
  254. if content_length == 0:
  255. self._stream = None
  256. elif not self._request._read_started:
  257. self._stream = self._request
  258. else:
  259. self._stream = io.BytesIO(self.body)
  260. def _supports_form_parsing(self):
  261. """
  262. Return True if this requests supports parsing form data.
  263. """
  264. form_media = (
  265. 'application/x-www-form-urlencoded',
  266. 'multipart/form-data'
  267. )
  268. return any(parser.media_type in form_media for parser in self.parsers)
  269. def _parse(self):
  270. """
  271. Parse the request content, returning a two-tuple of (data, files)
  272. May raise an `UnsupportedMediaType`, or `ParseError` exception.
  273. """
  274. media_type = self.content_type
  275. try:
  276. stream = self.stream
  277. except RawPostDataException:
  278. if not hasattr(self._request, '_post'):
  279. raise
  280. # If request.POST has been accessed in middleware, and a method='POST'
  281. # request was made with 'multipart/form-data', then the request stream
  282. # will already have been exhausted.
  283. if self._supports_form_parsing():
  284. return (self._request.POST, self._request.FILES)
  285. stream = None
  286. if stream is None or media_type is None:
  287. if media_type and is_form_media_type(media_type):
  288. empty_data = QueryDict('', encoding=self._request._encoding)
  289. else:
  290. empty_data = {}
  291. empty_files = MultiValueDict()
  292. return (empty_data, empty_files)
  293. parser = self.negotiator.select_parser(self, self.parsers)
  294. if not parser:
  295. raise exceptions.UnsupportedMediaType(media_type)
  296. try:
  297. parsed = parser.parse(stream, media_type, self.parser_context)
  298. except Exception:
  299. # If we get an exception during parsing, fill in empty data and
  300. # re-raise. Ensures we don't simply repeat the error when
  301. # attempting to render the browsable renderer response, or when
  302. # logging the request or similar.
  303. self._data = QueryDict('', encoding=self._request._encoding)
  304. self._files = MultiValueDict()
  305. self._full_data = self._data
  306. raise
  307. # Parser classes may return the raw data, or a
  308. # DataAndFiles object. Unpack the result as required.
  309. try:
  310. return (parsed.data, parsed.files)
  311. except AttributeError:
  312. empty_files = MultiValueDict()
  313. return (parsed, empty_files)
  314. def _authenticate(self):
  315. """
  316. Attempt to authenticate the request using each authentication instance
  317. in turn.
  318. """
  319. for authenticator in self.authenticators:
  320. try:
  321. user_auth_tuple = authenticator.authenticate(self)
  322. except exceptions.APIException:
  323. self._not_authenticated()
  324. raise
  325. if user_auth_tuple is not None:
  326. self._authenticator = authenticator
  327. self.user, self.auth = user_auth_tuple
  328. return
  329. self._not_authenticated()
  330. def _not_authenticated(self):
  331. """
  332. Set authenticator, user & authtoken representing an unauthenticated request.
  333. Defaults are None, AnonymousUser & None.
  334. """
  335. self._authenticator = None
  336. if api_settings.UNAUTHENTICATED_USER:
  337. self.user = api_settings.UNAUTHENTICATED_USER()
  338. else:
  339. self.user = None
  340. if api_settings.UNAUTHENTICATED_TOKEN:
  341. self.auth = api_settings.UNAUTHENTICATED_TOKEN()
  342. else:
  343. self.auth = None
  344. def __getattr__(self, attr):
  345. """
  346. If an attribute does not exist on this instance, then we also attempt
  347. to proxy it to the underlying HttpRequest object.
  348. """
  349. try:
  350. return getattr(self._request, attr)
  351. except AttributeError:
  352. return self.__getattribute__(attr)
  353. @property
  354. def DATA(self):
  355. raise NotImplementedError(
  356. '`request.DATA` has been deprecated in favor of `request.data` '
  357. 'since version 3.0, and has been fully removed as of version 3.2.'
  358. )
  359. @property
  360. def POST(self):
  361. # Ensure that request.POST uses our request parsing.
  362. if not _hasattr(self, '_data'):
  363. self._load_data_and_files()
  364. if is_form_media_type(self.content_type):
  365. return self._data
  366. return QueryDict('', encoding=self._request._encoding)
  367. @property
  368. def FILES(self):
  369. # Leave this one alone for backwards compat with Django's request.FILES
  370. # Different from the other two cases, which are not valid property
  371. # names on the WSGIRequest class.
  372. if not _hasattr(self, '_files'):
  373. self._load_data_and_files()
  374. return self._files
  375. @property
  376. def QUERY_PARAMS(self):
  377. raise NotImplementedError(
  378. '`request.QUERY_PARAMS` has been deprecated in favor of `request.query_params` '
  379. 'since version 3.0, and has been fully removed as of version 3.2.'
  380. )
  381. def force_plaintext_errors(self, value):
  382. # Hack to allow our exception handler to force choice of
  383. # plaintext or html error responses.
  384. self._request.is_ajax = lambda: value