Send file via Django Rest

I need to load an image object from different object storage codes and send it to the user through the Django Rest Framework.

I have something like this:

if request.method == 'GET':

    # Get object using swiftclient
    conn = swiftclient.client.Connection(**credentials)
    container, file = 'container_name', 'object_name'
    _, data = conn.get_object(container, file)

    # Send object to the browser
    return Response(data, content_type="image/png")

data the variable contains the type of bytes.

During testing, I get an error message: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

What could be the solution to this problem?

+4
source share
2 answers

You need to import base64 and you need to convert the data to base64 encoded byte format to solve this problem.

import base64 
data = base64.b64encode(data)

==== OR =====

I respect @ Reply to Keeling and would like to have this in my post.

from django.http import HttpResponse

return HttpResponse(data, content_type="image/png")
0
source

Django Rest Framework , HttpResponse.

from django.http import HttpResponse

...

return HttpResponse(data, content_type="image/png")

Django Rest Framework own Response , , .

+4

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


All Articles