5👍
I found a way to do this with a custom exception handler after all:
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 hoping for a better answer.
4👍
If request is ok and file exists, I read it as bytes and pass it to Response, as custom renderer I use PDFRenderer as yours. If request isn’t ok, I return json. My solution is to check if data is instance of bytes, if not, I just return bytes from valid json string, because render method should return bytes anyway
class PDFRenderer(BaseRenderer):
media_type = 'application/pdf'
format = 'pdf'
charset = None
render_style = 'binary'
def render(self, data, media_type=None, renderer_context=None):
if isinstance(data, bytes):
return data
data_to_response = json.dumps(data)
return bytes(data_to_response.encode('utf-8'))
- Django vs. Grok / Zope3 vs. Pylons
- Starting Scrapy from a Django view
- Creating custom Field Lookups in Django
- GenericForeignKey and Admin in Django
- Django – Allow duplicate usernames
Source:stackexchange.com