Serve images with django-rest-framework

久未见 提交于 2021-01-27 20:00:17

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/30889003/serve-images-with-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!