Override accepted render in django-rest-framework on exception

I use django-rest-framework to create an endpoint that returns a PDF file. However, when there is an error displaying the PDF file, I want to return a JSON response. But DRF does pass data to be excluded from my PDFRenderer class. How can I use JSONRenderer instead, only if there is an error?

class PDFRenderer(BaseRenderer):
    """ DRF renderer for PDF binary content. """
    media_type = 'application/pdf'
    format = 'pdf'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return bytes(data)

For example, when my view says raise PermissionDenied(), because the authorized user does not have permission to view the requested PDF file, {'detail': 'You do not have permission to perform this action.'}as an argument datafor PDFRenderer.render.

Edit: I tried a custom exception handler , but apparently you still have to run it through the DRF exception handler as well, which passes it to the PDFRenderer.

+4
source share
1 answer

I found a way to do this using a special exception handler:

from rest_framework.renderers import JSONRenderer
from rest_framework.views import exception_handler


def custom_exception_handler(exc, context):
    """ Switch from PDFRenderer to JSONRenderer for exceptions """
    if context['request'].accepted_renderer.format == 'pdf':
        context['request'].accepted_renderer = JSONRenderer()
    return exception_handler(exc, context)

It feels pretty hacky. Still hope for a better answer.

+1
source

Source: https://habr.com/ru/post/1683041/


All Articles