renderers.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. """
  2. Renderers are used to serialize a response into specific media types.
  3. They give us a generic way of being able to handle various media types
  4. on the response, such as JSON encoded data or HTML output.
  5. REST framework also provides an HTML renderer that renders the browsable API.
  6. """
  7. import base64
  8. from collections import OrderedDict
  9. from urllib import parse
  10. from django import forms
  11. from django.conf import settings
  12. from django.core.exceptions import ImproperlyConfigured
  13. from django.core.paginator import Page
  14. from django.http.multipartparser import parse_header
  15. from django.template import engines, loader
  16. from django.urls import NoReverseMatch
  17. from django.utils.html import mark_safe
  18. from rest_framework import VERSION, exceptions, serializers, status
  19. from rest_framework.compat import (
  20. INDENT_SEPARATORS, LONG_SEPARATORS, SHORT_SEPARATORS, coreapi, coreschema,
  21. pygments_css, yaml
  22. )
  23. from rest_framework.exceptions import ParseError
  24. from rest_framework.request import is_form_media_type, override_method
  25. from rest_framework.settings import api_settings
  26. from rest_framework.utils import encoders, json
  27. from rest_framework.utils.breadcrumbs import get_breadcrumbs
  28. from rest_framework.utils.field_mapping import ClassLookupDict
  29. def zero_as_none(value):
  30. return None if value == 0 else value
  31. class BaseRenderer:
  32. """
  33. All renderers should extend this class, setting the `media_type`
  34. and `format` attributes, and override the `.render()` method.
  35. """
  36. media_type = None
  37. format = None
  38. charset = 'utf-8'
  39. render_style = 'text'
  40. def render(self, data, accepted_media_type=None, renderer_context=None):
  41. raise NotImplementedError('Renderer class requires .render() to be implemented')
  42. class JSONRenderer(BaseRenderer):
  43. """
  44. Renderer which serializes to JSON.
  45. """
  46. media_type = 'application/json'
  47. format = 'json'
  48. encoder_class = encoders.JSONEncoder
  49. ensure_ascii = not api_settings.UNICODE_JSON
  50. compact = api_settings.COMPACT_JSON
  51. strict = api_settings.STRICT_JSON
  52. # We don't set a charset because JSON is a binary encoding,
  53. # that can be encoded as utf-8, utf-16 or utf-32.
  54. # See: https://www.ietf.org/rfc/rfc4627.txt
  55. # Also: http://lucumr.pocoo.org/2013/7/19/application-mimetypes-and-encodings/
  56. charset = None
  57. def get_indent(self, accepted_media_type, renderer_context):
  58. if accepted_media_type:
  59. # If the media type looks like 'application/json; indent=4',
  60. # then pretty print the result.
  61. # Note that we coerce `indent=0` into `indent=None`.
  62. base_media_type, params = parse_header(accepted_media_type.encode('ascii'))
  63. try:
  64. return zero_as_none(max(min(int(params['indent']), 8), 0))
  65. except (KeyError, ValueError, TypeError):
  66. pass
  67. # If 'indent' is provided in the context, then pretty print the result.
  68. # E.g. If we're being called by the BrowsableAPIRenderer.
  69. return renderer_context.get('indent', None)
  70. def render(self, data, accepted_media_type=None, renderer_context=None):
  71. """
  72. Render `data` into JSON, returning a bytestring.
  73. """
  74. if data is None:
  75. return b''
  76. renderer_context = renderer_context or {}
  77. indent = self.get_indent(accepted_media_type, renderer_context)
  78. if indent is None:
  79. separators = SHORT_SEPARATORS if self.compact else LONG_SEPARATORS
  80. else:
  81. separators = INDENT_SEPARATORS
  82. ret = json.dumps(
  83. data, cls=self.encoder_class,
  84. indent=indent, ensure_ascii=self.ensure_ascii,
  85. allow_nan=not self.strict, separators=separators
  86. )
  87. # We always fully escape \u2028 and \u2029 to ensure we output JSON
  88. # that is a strict javascript subset.
  89. # See: http://timelessrepo.com/json-isnt-a-javascript-subset
  90. ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
  91. return ret.encode()
  92. class TemplateHTMLRenderer(BaseRenderer):
  93. """
  94. An HTML renderer for use with templates.
  95. The data supplied to the Response object should be a dictionary that will
  96. be used as context for the template.
  97. The template name is determined by (in order of preference):
  98. 1. An explicit `.template_name` attribute set on the response.
  99. 2. An explicit `.template_name` attribute set on this class.
  100. 3. The return result of calling `view.get_template_names()`.
  101. For example:
  102. data = {'users': User.objects.all()}
  103. return Response(data, template_name='users.html')
  104. For pre-rendered HTML, see StaticHTMLRenderer.
  105. """
  106. media_type = 'text/html'
  107. format = 'html'
  108. template_name = None
  109. exception_template_names = [
  110. '%(status_code)s.html',
  111. 'api_exception.html'
  112. ]
  113. charset = 'utf-8'
  114. def render(self, data, accepted_media_type=None, renderer_context=None):
  115. """
  116. Renders data to HTML, using Django's standard template rendering.
  117. The template name is determined by (in order of preference):
  118. 1. An explicit .template_name set on the response.
  119. 2. An explicit .template_name set on this class.
  120. 3. The return result of calling view.get_template_names().
  121. """
  122. renderer_context = renderer_context or {}
  123. view = renderer_context['view']
  124. request = renderer_context['request']
  125. response = renderer_context['response']
  126. if response.exception:
  127. template = self.get_exception_template(response)
  128. else:
  129. template_names = self.get_template_names(response, view)
  130. template = self.resolve_template(template_names)
  131. if hasattr(self, 'resolve_context'):
  132. # Fallback for older versions.
  133. context = self.resolve_context(data, request, response)
  134. else:
  135. context = self.get_template_context(data, renderer_context)
  136. return template.render(context, request=request)
  137. def resolve_template(self, template_names):
  138. return loader.select_template(template_names)
  139. def get_template_context(self, data, renderer_context):
  140. response = renderer_context['response']
  141. if response.exception:
  142. data['status_code'] = response.status_code
  143. return data
  144. def get_template_names(self, response, view):
  145. if response.template_name:
  146. return [response.template_name]
  147. elif self.template_name:
  148. return [self.template_name]
  149. elif hasattr(view, 'get_template_names'):
  150. return view.get_template_names()
  151. elif hasattr(view, 'template_name'):
  152. return [view.template_name]
  153. raise ImproperlyConfigured(
  154. 'Returned a template response with no `template_name` attribute set on either the view or response'
  155. )
  156. def get_exception_template(self, response):
  157. template_names = [name % {'status_code': response.status_code}
  158. for name in self.exception_template_names]
  159. try:
  160. # Try to find an appropriate error template
  161. return self.resolve_template(template_names)
  162. except Exception:
  163. # Fall back to using eg '404 Not Found'
  164. body = '%d %s' % (response.status_code, response.status_text.title())
  165. template = engines['django'].from_string(body)
  166. return template
  167. # Note, subclass TemplateHTMLRenderer simply for the exception behavior
  168. class StaticHTMLRenderer(TemplateHTMLRenderer):
  169. """
  170. An HTML renderer class that simply returns pre-rendered HTML.
  171. The data supplied to the Response object should be a string representing
  172. the pre-rendered HTML content.
  173. For example:
  174. data = '<html><body>example</body></html>'
  175. return Response(data)
  176. For template rendered HTML, see TemplateHTMLRenderer.
  177. """
  178. media_type = 'text/html'
  179. format = 'html'
  180. charset = 'utf-8'
  181. def render(self, data, accepted_media_type=None, renderer_context=None):
  182. renderer_context = renderer_context or {}
  183. response = renderer_context.get('response')
  184. if response and response.exception:
  185. request = renderer_context['request']
  186. template = self.get_exception_template(response)
  187. if hasattr(self, 'resolve_context'):
  188. context = self.resolve_context(data, request, response)
  189. else:
  190. context = self.get_template_context(data, renderer_context)
  191. return template.render(context, request=request)
  192. return data
  193. class HTMLFormRenderer(BaseRenderer):
  194. """
  195. Renderers serializer data into an HTML form.
  196. If the serializer was instantiated without an object then this will
  197. return an HTML form not bound to any object,
  198. otherwise it will return an HTML form with the appropriate initial data
  199. populated from the object.
  200. Note that rendering of field and form errors is not currently supported.
  201. """
  202. media_type = 'text/html'
  203. format = 'form'
  204. charset = 'utf-8'
  205. template_pack = 'rest_framework/vertical/'
  206. base_template = 'form.html'
  207. default_style = ClassLookupDict({
  208. serializers.Field: {
  209. 'base_template': 'input.html',
  210. 'input_type': 'text'
  211. },
  212. serializers.EmailField: {
  213. 'base_template': 'input.html',
  214. 'input_type': 'email'
  215. },
  216. serializers.URLField: {
  217. 'base_template': 'input.html',
  218. 'input_type': 'url'
  219. },
  220. serializers.IntegerField: {
  221. 'base_template': 'input.html',
  222. 'input_type': 'number'
  223. },
  224. serializers.FloatField: {
  225. 'base_template': 'input.html',
  226. 'input_type': 'number'
  227. },
  228. serializers.DateTimeField: {
  229. 'base_template': 'input.html',
  230. 'input_type': 'datetime-local'
  231. },
  232. serializers.DateField: {
  233. 'base_template': 'input.html',
  234. 'input_type': 'date'
  235. },
  236. serializers.TimeField: {
  237. 'base_template': 'input.html',
  238. 'input_type': 'time'
  239. },
  240. serializers.FileField: {
  241. 'base_template': 'input.html',
  242. 'input_type': 'file'
  243. },
  244. serializers.BooleanField: {
  245. 'base_template': 'checkbox.html'
  246. },
  247. serializers.ChoiceField: {
  248. 'base_template': 'select.html', # Also valid: 'radio.html'
  249. },
  250. serializers.MultipleChoiceField: {
  251. 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html'
  252. },
  253. serializers.RelatedField: {
  254. 'base_template': 'select.html', # Also valid: 'radio.html'
  255. },
  256. serializers.ManyRelatedField: {
  257. 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html'
  258. },
  259. serializers.Serializer: {
  260. 'base_template': 'fieldset.html'
  261. },
  262. serializers.ListSerializer: {
  263. 'base_template': 'list_fieldset.html'
  264. },
  265. serializers.ListField: {
  266. 'base_template': 'list_field.html'
  267. },
  268. serializers.DictField: {
  269. 'base_template': 'dict_field.html'
  270. },
  271. serializers.FilePathField: {
  272. 'base_template': 'select.html',
  273. },
  274. serializers.JSONField: {
  275. 'base_template': 'textarea.html',
  276. },
  277. })
  278. def render_field(self, field, parent_style):
  279. if isinstance(field._field, serializers.HiddenField):
  280. return ''
  281. style = self.default_style[field].copy()
  282. style.update(field.style)
  283. if 'template_pack' not in style:
  284. style['template_pack'] = parent_style.get('template_pack', self.template_pack)
  285. style['renderer'] = self
  286. # Get a clone of the field with text-only value representation.
  287. field = field.as_form_field()
  288. if style.get('input_type') == 'datetime-local' and isinstance(field.value, str):
  289. field.value = field.value.rstrip('Z')
  290. if 'template' in style:
  291. template_name = style['template']
  292. else:
  293. template_name = style['template_pack'].strip('/') + '/' + style['base_template']
  294. template = loader.get_template(template_name)
  295. context = {'field': field, 'style': style}
  296. return template.render(context)
  297. def render(self, data, accepted_media_type=None, renderer_context=None):
  298. """
  299. Render serializer data and return an HTML form, as a string.
  300. """
  301. renderer_context = renderer_context or {}
  302. form = data.serializer
  303. style = renderer_context.get('style', {})
  304. if 'template_pack' not in style:
  305. style['template_pack'] = self.template_pack
  306. style['renderer'] = self
  307. template_pack = style['template_pack'].strip('/')
  308. template_name = template_pack + '/' + self.base_template
  309. template = loader.get_template(template_name)
  310. context = {
  311. 'form': form,
  312. 'style': style
  313. }
  314. return template.render(context)
  315. class BrowsableAPIRenderer(BaseRenderer):
  316. """
  317. HTML renderer used to self-document the API.
  318. """
  319. media_type = 'text/html'
  320. format = 'api'
  321. template = 'rest_framework/api.html'
  322. filter_template = 'rest_framework/filters/base.html'
  323. code_style = 'emacs'
  324. charset = 'utf-8'
  325. form_renderer_class = HTMLFormRenderer
  326. def get_default_renderer(self, view):
  327. """
  328. Return an instance of the first valid renderer.
  329. (Don't use another documenting renderer.)
  330. """
  331. renderers = [renderer for renderer in view.renderer_classes
  332. if not issubclass(renderer, BrowsableAPIRenderer)]
  333. non_template_renderers = [renderer for renderer in renderers
  334. if not hasattr(renderer, 'get_template_names')]
  335. if not renderers:
  336. return None
  337. elif non_template_renderers:
  338. return non_template_renderers[0]()
  339. return renderers[0]()
  340. def get_content(self, renderer, data,
  341. accepted_media_type, renderer_context):
  342. """
  343. Get the content as if it had been rendered by the default
  344. non-documenting renderer.
  345. """
  346. if not renderer:
  347. return '[No renderers were found]'
  348. renderer_context['indent'] = 4
  349. content = renderer.render(data, accepted_media_type, renderer_context)
  350. render_style = getattr(renderer, 'render_style', 'text')
  351. assert render_style in ['text', 'binary'], 'Expected .render_style ' \
  352. '"text" or "binary", but got "%s"' % render_style
  353. if render_style == 'binary':
  354. return '[%d bytes of binary content]' % len(content)
  355. return content.decode('utf-8') if isinstance(content, bytes) else content
  356. def show_form_for_method(self, view, method, request, obj):
  357. """
  358. Returns True if a form should be shown for this method.
  359. """
  360. if method not in view.allowed_methods:
  361. return # Not a valid method
  362. try:
  363. view.check_permissions(request)
  364. if obj is not None:
  365. view.check_object_permissions(request, obj)
  366. except exceptions.APIException:
  367. return False # Doesn't have permissions
  368. return True
  369. def _get_serializer(self, serializer_class, view_instance, request, *args, **kwargs):
  370. kwargs['context'] = {
  371. 'request': request,
  372. 'format': self.format,
  373. 'view': view_instance
  374. }
  375. return serializer_class(*args, **kwargs)
  376. def get_rendered_html_form(self, data, view, method, request):
  377. """
  378. Return a string representing a rendered HTML form, possibly bound to
  379. either the input or output data.
  380. In the absence of the View having an associated form then return None.
  381. """
  382. # See issue #2089 for refactoring this.
  383. serializer = getattr(data, 'serializer', None)
  384. if serializer and not getattr(serializer, 'many', False):
  385. instance = getattr(serializer, 'instance', None)
  386. if isinstance(instance, Page):
  387. instance = None
  388. else:
  389. instance = None
  390. # If this is valid serializer data, and the form is for the same
  391. # HTTP method as was used in the request then use the existing
  392. # serializer instance, rather than dynamically creating a new one.
  393. if request.method == method and serializer is not None:
  394. try:
  395. kwargs = {'data': request.data}
  396. except ParseError:
  397. kwargs = {}
  398. existing_serializer = serializer
  399. else:
  400. kwargs = {}
  401. existing_serializer = None
  402. with override_method(view, request, method) as request:
  403. if not self.show_form_for_method(view, method, request, instance):
  404. return
  405. if method in ('DELETE', 'OPTIONS'):
  406. return True # Don't actually need to return a form
  407. has_serializer = getattr(view, 'get_serializer', None)
  408. has_serializer_class = getattr(view, 'serializer_class', None)
  409. if (
  410. (not has_serializer and not has_serializer_class) or
  411. not any(is_form_media_type(parser.media_type) for parser in view.parser_classes)
  412. ):
  413. return
  414. if existing_serializer is not None:
  415. try:
  416. return self.render_form_for_serializer(existing_serializer)
  417. except TypeError:
  418. pass
  419. if has_serializer:
  420. if method in ('PUT', 'PATCH'):
  421. serializer = view.get_serializer(instance=instance, **kwargs)
  422. else:
  423. serializer = view.get_serializer(**kwargs)
  424. else:
  425. # at this point we must have a serializer_class
  426. if method in ('PUT', 'PATCH'):
  427. serializer = self._get_serializer(view.serializer_class, view,
  428. request, instance=instance, **kwargs)
  429. else:
  430. serializer = self._get_serializer(view.serializer_class, view,
  431. request, **kwargs)
  432. return self.render_form_for_serializer(serializer)
  433. def render_form_for_serializer(self, serializer):
  434. if hasattr(serializer, 'initial_data'):
  435. serializer.is_valid()
  436. form_renderer = self.form_renderer_class()
  437. return form_renderer.render(
  438. serializer.data,
  439. self.accepted_media_type,
  440. {'style': {'template_pack': 'rest_framework/horizontal'}}
  441. )
  442. def get_raw_data_form(self, data, view, method, request):
  443. """
  444. Returns a form that allows for arbitrary content types to be tunneled
  445. via standard HTML forms.
  446. (Which are typically application/x-www-form-urlencoded)
  447. """
  448. # See issue #2089 for refactoring this.
  449. serializer = getattr(data, 'serializer', None)
  450. if serializer and not getattr(serializer, 'many', False):
  451. instance = getattr(serializer, 'instance', None)
  452. if isinstance(instance, Page):
  453. instance = None
  454. else:
  455. instance = None
  456. with override_method(view, request, method) as request:
  457. # Check permissions
  458. if not self.show_form_for_method(view, method, request, instance):
  459. return
  460. # If possible, serialize the initial content for the generic form
  461. default_parser = view.parser_classes[0]
  462. renderer_class = getattr(default_parser, 'renderer_class', None)
  463. if hasattr(view, 'get_serializer') and renderer_class:
  464. # View has a serializer defined and parser class has a
  465. # corresponding renderer that can be used to render the data.
  466. if method in ('PUT', 'PATCH'):
  467. serializer = view.get_serializer(instance=instance)
  468. else:
  469. serializer = view.get_serializer()
  470. # Render the raw data content
  471. renderer = renderer_class()
  472. accepted = self.accepted_media_type
  473. context = self.renderer_context.copy()
  474. context['indent'] = 4
  475. # strip HiddenField from output
  476. data = serializer.data.copy()
  477. for name, field in serializer.fields.items():
  478. if isinstance(field, serializers.HiddenField):
  479. data.pop(name, None)
  480. content = renderer.render(data, accepted, context)
  481. # Renders returns bytes, but CharField expects a str.
  482. content = content.decode()
  483. else:
  484. content = None
  485. # Generate a generic form that includes a content type field,
  486. # and a content field.
  487. media_types = [parser.media_type for parser in view.parser_classes]
  488. choices = [(media_type, media_type) for media_type in media_types]
  489. initial = media_types[0]
  490. class GenericContentForm(forms.Form):
  491. _content_type = forms.ChoiceField(
  492. label='Media type',
  493. choices=choices,
  494. initial=initial,
  495. widget=forms.Select(attrs={'data-override': 'content-type'})
  496. )
  497. _content = forms.CharField(
  498. label='Content',
  499. widget=forms.Textarea(attrs={'data-override': 'content'}),
  500. initial=content,
  501. required=False
  502. )
  503. return GenericContentForm()
  504. def get_name(self, view):
  505. return view.get_view_name()
  506. def get_description(self, view, status_code):
  507. if status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN):
  508. return ''
  509. return view.get_view_description(html=True)
  510. def get_breadcrumbs(self, request):
  511. return get_breadcrumbs(request.path, request)
  512. def get_extra_actions(self, view, status_code):
  513. if (status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)):
  514. return None
  515. elif not hasattr(view, 'get_extra_action_url_map'):
  516. return None
  517. return view.get_extra_action_url_map()
  518. def get_filter_form(self, data, view, request):
  519. if not hasattr(view, 'get_queryset') or not hasattr(view, 'filter_backends'):
  520. return
  521. # Infer if this is a list view or not.
  522. paginator = getattr(view, 'paginator', None)
  523. if isinstance(data, list):
  524. pass
  525. elif paginator is not None and data is not None:
  526. try:
  527. paginator.get_results(data)
  528. except (TypeError, KeyError):
  529. return
  530. elif not isinstance(data, list):
  531. return
  532. queryset = view.get_queryset()
  533. elements = []
  534. for backend in view.filter_backends:
  535. if hasattr(backend, 'to_html'):
  536. html = backend().to_html(request, queryset, view)
  537. if html:
  538. elements.append(html)
  539. if not elements:
  540. return
  541. template = loader.get_template(self.filter_template)
  542. context = {'elements': elements}
  543. return template.render(context)
  544. def get_context(self, data, accepted_media_type, renderer_context):
  545. """
  546. Returns the context used to render.
  547. """
  548. view = renderer_context['view']
  549. request = renderer_context['request']
  550. response = renderer_context['response']
  551. renderer = self.get_default_renderer(view)
  552. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)
  553. raw_data_put_form = self.get_raw_data_form(data, view, 'PUT', request)
  554. raw_data_patch_form = self.get_raw_data_form(data, view, 'PATCH', request)
  555. raw_data_put_or_patch_form = raw_data_put_form or raw_data_patch_form
  556. response_headers = OrderedDict(sorted(response.items()))
  557. renderer_content_type = ''
  558. if renderer:
  559. renderer_content_type = '%s' % renderer.media_type
  560. if renderer.charset:
  561. renderer_content_type += ' ;%s' % renderer.charset
  562. response_headers['Content-Type'] = renderer_content_type
  563. if getattr(view, 'paginator', None) and view.paginator.display_page_controls:
  564. paginator = view.paginator
  565. else:
  566. paginator = None
  567. csrf_cookie_name = settings.CSRF_COOKIE_NAME
  568. csrf_header_name = settings.CSRF_HEADER_NAME
  569. if csrf_header_name.startswith('HTTP_'):
  570. csrf_header_name = csrf_header_name[5:]
  571. csrf_header_name = csrf_header_name.replace('_', '-')
  572. return {
  573. 'content': self.get_content(renderer, data, accepted_media_type, renderer_context),
  574. 'code_style': pygments_css(self.code_style),
  575. 'view': view,
  576. 'request': request,
  577. 'response': response,
  578. 'user': request.user,
  579. 'description': self.get_description(view, response.status_code),
  580. 'name': self.get_name(view),
  581. 'version': VERSION,
  582. 'paginator': paginator,
  583. 'breadcrumblist': self.get_breadcrumbs(request),
  584. 'allowed_methods': view.allowed_methods,
  585. 'available_formats': [renderer_cls.format for renderer_cls in view.renderer_classes],
  586. 'response_headers': response_headers,
  587. 'put_form': self.get_rendered_html_form(data, view, 'PUT', request),
  588. 'post_form': self.get_rendered_html_form(data, view, 'POST', request),
  589. 'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request),
  590. 'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request),
  591. 'extra_actions': self.get_extra_actions(view, response.status_code),
  592. 'filter_form': self.get_filter_form(data, view, request),
  593. 'raw_data_put_form': raw_data_put_form,
  594. 'raw_data_post_form': raw_data_post_form,
  595. 'raw_data_patch_form': raw_data_patch_form,
  596. 'raw_data_put_or_patch_form': raw_data_put_or_patch_form,
  597. 'display_edit_forms': bool(response.status_code != 403),
  598. 'api_settings': api_settings,
  599. 'csrf_cookie_name': csrf_cookie_name,
  600. 'csrf_header_name': csrf_header_name
  601. }
  602. def render(self, data, accepted_media_type=None, renderer_context=None):
  603. """
  604. Render the HTML for the browsable API representation.
  605. """
  606. self.accepted_media_type = accepted_media_type or ''
  607. self.renderer_context = renderer_context or {}
  608. template = loader.get_template(self.template)
  609. context = self.get_context(data, accepted_media_type, renderer_context)
  610. ret = template.render(context, request=renderer_context['request'])
  611. # Munge DELETE Response code to allow us to return content
  612. # (Do this *after* we've rendered the template so that we include
  613. # the normal deletion response code in the output)
  614. response = renderer_context['response']
  615. if response.status_code == status.HTTP_204_NO_CONTENT:
  616. response.status_code = status.HTTP_200_OK
  617. return ret
  618. class AdminRenderer(BrowsableAPIRenderer):
  619. template = 'rest_framework/admin.html'
  620. format = 'admin'
  621. def render(self, data, accepted_media_type=None, renderer_context=None):
  622. self.accepted_media_type = accepted_media_type or ''
  623. self.renderer_context = renderer_context or {}
  624. response = renderer_context['response']
  625. request = renderer_context['request']
  626. view = self.renderer_context['view']
  627. if response.status_code == status.HTTP_400_BAD_REQUEST:
  628. # Errors still need to display the list or detail information.
  629. # The only way we can get at that is to simulate a GET request.
  630. self.error_form = self.get_rendered_html_form(data, view, request.method, request)
  631. self.error_title = {'POST': 'Create', 'PUT': 'Edit'}.get(request.method, 'Errors')
  632. with override_method(view, request, 'GET') as request:
  633. response = view.get(request, *view.args, **view.kwargs)
  634. data = response.data
  635. template = loader.get_template(self.template)
  636. context = self.get_context(data, accepted_media_type, renderer_context)
  637. ret = template.render(context, request=renderer_context['request'])
  638. # Creation and deletion should use redirects in the admin style.
  639. if response.status_code == status.HTTP_201_CREATED and 'Location' in response:
  640. response.status_code = status.HTTP_303_SEE_OTHER
  641. response['Location'] = request.build_absolute_uri()
  642. ret = ''
  643. if response.status_code == status.HTTP_204_NO_CONTENT:
  644. response.status_code = status.HTTP_303_SEE_OTHER
  645. try:
  646. # Attempt to get the parent breadcrumb URL.
  647. response['Location'] = self.get_breadcrumbs(request)[-2][1]
  648. except KeyError:
  649. # Otherwise reload current URL to get a 'Not Found' page.
  650. response['Location'] = request.full_path
  651. ret = ''
  652. return ret
  653. def get_context(self, data, accepted_media_type, renderer_context):
  654. """
  655. Render the HTML for the browsable API representation.
  656. """
  657. context = super().get_context(
  658. data, accepted_media_type, renderer_context
  659. )
  660. paginator = getattr(context['view'], 'paginator', None)
  661. if paginator is not None and data is not None:
  662. try:
  663. results = paginator.get_results(data)
  664. except (TypeError, KeyError):
  665. results = data
  666. else:
  667. results = data
  668. if results is None:
  669. header = {}
  670. style = 'detail'
  671. elif isinstance(results, list):
  672. header = results[0] if results else {}
  673. style = 'list'
  674. else:
  675. header = results
  676. style = 'detail'
  677. columns = [key for key in header if key != 'url']
  678. details = [key for key in header if key != 'url']
  679. if isinstance(results, list) and 'view' in renderer_context:
  680. for result in results:
  681. url = self.get_result_url(result, context['view'])
  682. if url is not None:
  683. result.setdefault('url', url)
  684. context['style'] = style
  685. context['columns'] = columns
  686. context['details'] = details
  687. context['results'] = results
  688. context['error_form'] = getattr(self, 'error_form', None)
  689. context['error_title'] = getattr(self, 'error_title', None)
  690. return context
  691. def get_result_url(self, result, view):
  692. """
  693. Attempt to reverse the result's detail view URL.
  694. This only works with views that are generic-like (has `.lookup_field`)
  695. and viewset-like (has `.basename` / `.reverse_action()`).
  696. """
  697. if not hasattr(view, 'reverse_action') or \
  698. not hasattr(view, 'lookup_field'):
  699. return
  700. lookup_field = view.lookup_field
  701. lookup_url_kwarg = getattr(view, 'lookup_url_kwarg', None) or lookup_field
  702. try:
  703. kwargs = {lookup_url_kwarg: result[lookup_field]}
  704. return view.reverse_action('detail', kwargs=kwargs)
  705. except (KeyError, NoReverseMatch):
  706. return
  707. class DocumentationRenderer(BaseRenderer):
  708. media_type = 'text/html'
  709. format = 'html'
  710. charset = 'utf-8'
  711. template = 'rest_framework/docs/index.html'
  712. error_template = 'rest_framework/docs/error.html'
  713. code_style = 'emacs'
  714. languages = ['shell', 'javascript', 'python']
  715. def get_context(self, data, request):
  716. return {
  717. 'document': data,
  718. 'langs': self.languages,
  719. 'lang_htmls': ["rest_framework/docs/langs/%s.html" % language for language in self.languages],
  720. 'lang_intro_htmls': ["rest_framework/docs/langs/%s-intro.html" % language for language in self.languages],
  721. 'code_style': pygments_css(self.code_style),
  722. 'request': request
  723. }
  724. def render(self, data, accepted_media_type=None, renderer_context=None):
  725. if isinstance(data, coreapi.Document):
  726. template = loader.get_template(self.template)
  727. context = self.get_context(data, renderer_context['request'])
  728. return template.render(context, request=renderer_context['request'])
  729. else:
  730. template = loader.get_template(self.error_template)
  731. context = {
  732. "data": data,
  733. "request": renderer_context['request'],
  734. "response": renderer_context['response'],
  735. "debug": settings.DEBUG,
  736. }
  737. return template.render(context, request=renderer_context['request'])
  738. class SchemaJSRenderer(BaseRenderer):
  739. media_type = 'application/javascript'
  740. format = 'javascript'
  741. charset = 'utf-8'
  742. template = 'rest_framework/schema.js'
  743. def render(self, data, accepted_media_type=None, renderer_context=None):
  744. codec = coreapi.codecs.CoreJSONCodec()
  745. schema = base64.b64encode(codec.encode(data)).decode('ascii')
  746. template = loader.get_template(self.template)
  747. context = {'schema': mark_safe(schema)}
  748. request = renderer_context['request']
  749. return template.render(context, request=request)
  750. class MultiPartRenderer(BaseRenderer):
  751. media_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
  752. format = 'multipart'
  753. charset = 'utf-8'
  754. BOUNDARY = 'BoUnDaRyStRiNg'
  755. def render(self, data, accepted_media_type=None, renderer_context=None):
  756. from django.test.client import encode_multipart
  757. if hasattr(data, 'items'):
  758. for key, value in data.items():
  759. assert not isinstance(value, dict), (
  760. "Test data contained a dictionary value for key '%s', "
  761. "but multipart uploads do not support nested data. "
  762. "You may want to consider using format='json' in this "
  763. "test case." % key
  764. )
  765. return encode_multipart(self.BOUNDARY, data)
  766. class CoreJSONRenderer(BaseRenderer):
  767. media_type = 'application/coreapi+json'
  768. charset = None
  769. format = 'corejson'
  770. def __init__(self):
  771. assert coreapi, 'Using CoreJSONRenderer, but `coreapi` is not installed.'
  772. def render(self, data, media_type=None, renderer_context=None):
  773. indent = bool(renderer_context.get('indent', 0))
  774. codec = coreapi.codecs.CoreJSONCodec()
  775. return codec.dump(data, indent=indent)
  776. class _BaseOpenAPIRenderer:
  777. def get_schema(self, instance):
  778. CLASS_TO_TYPENAME = {
  779. coreschema.Object: 'object',
  780. coreschema.Array: 'array',
  781. coreschema.Number: 'number',
  782. coreschema.Integer: 'integer',
  783. coreschema.String: 'string',
  784. coreschema.Boolean: 'boolean',
  785. }
  786. schema = {}
  787. if instance.__class__ in CLASS_TO_TYPENAME:
  788. schema['type'] = CLASS_TO_TYPENAME[instance.__class__]
  789. schema['title'] = instance.title
  790. schema['description'] = instance.description
  791. if hasattr(instance, 'enum'):
  792. schema['enum'] = instance.enum
  793. return schema
  794. def get_parameters(self, link):
  795. parameters = []
  796. for field in link.fields:
  797. if field.location not in ['path', 'query']:
  798. continue
  799. parameter = {
  800. 'name': field.name,
  801. 'in': field.location,
  802. }
  803. if field.required:
  804. parameter['required'] = True
  805. if field.description:
  806. parameter['description'] = field.description
  807. if field.schema:
  808. parameter['schema'] = self.get_schema(field.schema)
  809. parameters.append(parameter)
  810. return parameters
  811. def get_operation(self, link, name, tag):
  812. operation_id = "%s_%s" % (tag, name) if tag else name
  813. parameters = self.get_parameters(link)
  814. operation = {
  815. 'operationId': operation_id,
  816. }
  817. if link.title:
  818. operation['summary'] = link.title
  819. if link.description:
  820. operation['description'] = link.description
  821. if parameters:
  822. operation['parameters'] = parameters
  823. if tag:
  824. operation['tags'] = [tag]
  825. return operation
  826. def get_paths(self, document):
  827. paths = {}
  828. tag = None
  829. for name, link in document.links.items():
  830. path = parse.urlparse(link.url).path
  831. method = link.action.lower()
  832. paths.setdefault(path, {})
  833. paths[path][method] = self.get_operation(link, name, tag=tag)
  834. for tag, section in document.data.items():
  835. for name, link in section.links.items():
  836. path = parse.urlparse(link.url).path
  837. method = link.action.lower()
  838. paths.setdefault(path, {})
  839. paths[path][method] = self.get_operation(link, name, tag=tag)
  840. return paths
  841. def get_structure(self, data):
  842. return {
  843. 'openapi': '3.0.0',
  844. 'info': {
  845. 'version': '',
  846. 'title': data.title,
  847. 'description': data.description
  848. },
  849. 'servers': [{
  850. 'url': data.url
  851. }],
  852. 'paths': self.get_paths(data)
  853. }
  854. class CoreAPIOpenAPIRenderer(_BaseOpenAPIRenderer):
  855. media_type = 'application/vnd.oai.openapi'
  856. charset = None
  857. format = 'openapi'
  858. def __init__(self):
  859. assert coreapi, 'Using CoreAPIOpenAPIRenderer, but `coreapi` is not installed.'
  860. assert yaml, 'Using CoreAPIOpenAPIRenderer, but `pyyaml` is not installed.'
  861. def render(self, data, media_type=None, renderer_context=None):
  862. structure = self.get_structure(data)
  863. return yaml.dump(structure, default_flow_style=False).encode()
  864. class CoreAPIJSONOpenAPIRenderer(_BaseOpenAPIRenderer):
  865. media_type = 'application/vnd.oai.openapi+json'
  866. charset = None
  867. format = 'openapi-json'
  868. ensure_ascii = not api_settings.UNICODE_JSON
  869. def __init__(self):
  870. assert coreapi, 'Using CoreAPIJSONOpenAPIRenderer, but `coreapi` is not installed.'
  871. def render(self, data, media_type=None, renderer_context=None):
  872. structure = self.get_structure(data)
  873. return json.dumps(
  874. structure, indent=4,
  875. ensure_ascii=self.ensure_ascii).encode('utf-8')
  876. class OpenAPIRenderer(BaseRenderer):
  877. media_type = 'application/vnd.oai.openapi'
  878. charset = None
  879. format = 'openapi'
  880. def __init__(self):
  881. assert yaml, 'Using OpenAPIRenderer, but `pyyaml` is not installed.'
  882. def render(self, data, media_type=None, renderer_context=None):
  883. # disable yaml advanced feature 'alias' for clean, portable, and readable output
  884. class Dumper(yaml.Dumper):
  885. def ignore_aliases(self, data):
  886. return True
  887. return yaml.dump(data, default_flow_style=False, sort_keys=False, Dumper=Dumper).encode('utf-8')
  888. class JSONOpenAPIRenderer(BaseRenderer):
  889. media_type = 'application/vnd.oai.openapi+json'
  890. charset = None
  891. encoder_class = encoders.JSONEncoder
  892. format = 'openapi-json'
  893. ensure_ascii = not api_settings.UNICODE_JSON
  894. def render(self, data, media_type=None, renderer_context=None):
  895. return json.dumps(
  896. data, cls=self.encoder_class, indent=2,
  897. ensure_ascii=self.ensure_ascii).encode('utf-8')