Reputation: 4711
I am trying to serve images from an api based on django-rest-api.
So far I have a very basic api view that loads an image and its mimetype and returns it.
@api_view(['GET'])
def get_pic(request, pk=None, format=None):
//get image and mimetype here
return HttpResponse(image, content_type=mimetype)
This has been working fine, however I have tested it on some new image libraries on iOS and have found that the API is returning a 406 error.
I believe this is because the client is sending a Accept image/* which this api view doesn't except.
Doing a HEAD on the api returns the following;
GET, OPTIONS
Connection → keep-alive
Content-Type → application/json
Date → Wed, 17 Jun 2015 10:11:07 GMT
Server → gunicorn/19.2.1
Transfer-Encoding → chunked
Vary → Accept, Cookie
Via → 1.1 vegur
X-Frame-Options → SAMEORIGIN
How can I change the Content-Type for this API to accept image requests?
I Have tried adding a custom parser with the right media_type but his doesn't seem to help. Is this the right approach or is there an easier way to serve images from django-rest-framework?
Upvotes: 3
Views: 2628
Reputation: 96
You need to create a custom renderer like:
class JPEGRenderer(renderers.BaseRenderer):
media_type = 'image/jpeg'
format = 'jpg'
charset = None
render_style = 'binary'
def render(self, data, media_type=None, renderer_context=None):
return data
Upvotes: 1