Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning binary data with django HttpResponse

I'm trying to get Django's HttpResponse to return binary data without much success. I've been trying different methods for a while now, but without success.

Encoding the string to ASCII works as long as the binary data values aren't outside the ASCII char scope, which is smaller than 0-255. The same happened when encoding with latin-1.

Creating byte string works nicely, but seems to fail if certain values are included, for example, if I have the following bytes included in the data: "\xf6\x52", I will get different bytes as a result. For some reason, the first byte, \xf6, gets converted to 0xfffd when I'm trying to review the result response.

I'd love to get some feedback and help with this.

Many thanks!

-A-

like image 268
user3144420 Avatar asked Mar 08 '14 23:03

user3144420


People also ask

What is HttpResponse in Django?

HttpResponse Methods – Django It is used to instantiate an HttpResponse object with the given page content and content type. HttpResponse.__setitem__(header, value) It is used to set the given header name to the given value.

What is get and post method in Django?

GET and POSTDjango's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.

What is request Meta in Django?

HttpRequest. META. A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples: CONTENT_LENGTH – The length of the request body (as a string).


2 Answers

return HttpResponse(data, content_type='application/octet-stream')

worked for me.

like image 158
sadashiv30 Avatar answered Oct 24 '22 04:10

sadashiv30


A flexible way to return binary data from Django is to first encode the data using Base64.

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

Since the Base64 encoded data is ASCII, the default HTTP response content type of text/html; charset=utf-8 works fine.

Image Example

Django

import base64
from io import BytesIO

from django.http import HttpRequest, HttpResponse
import PIL.Image


def image_test(request: HttpRequest) -> HttpResponse:
    file_stream = BytesIO()
    image_data = PIL.Image.open('/path/to/image.png')
    image_data.save(file_stream)
    file_stream.seek(0)
    base64_data = base64.b64encode(file_stream.getvalue()).decode('utf-8')
    return HttpResponse(base64_data)

Web Browser

After fetching the data from Django, the base64 data can be used to create a data URL.


// `data` fetched from Django as Base64 string
const dataURL = `data:image/png;base64,${data}`;
const newImage = new Image();
newImage.src = dataURL;
$('#ImageContainer').html(newImage);

JSON Response

The Base64 data may also be returned as part of a JSON response:

import base64
from io import BytesIO

from django.http import HttpRequest, JsonResponse
import PIL.Image

def image_test(request: HttpRequest) -> JsonResponse:
    file_stream = BytesIO()
    image_data = PIL.Image.open('/path/to/image.png')
    image_data.save(file_stream)
    file_stream.seek(0)
    base64_data = base64.b64encode(file_stream.getvalue()).decode('utf-8')
    json_data = dict()
    json_data['base64Data'] = base64_data
    return JsonResponse(json_data)
like image 39
Christopher Peisert Avatar answered Oct 24 '22 05:10

Christopher Peisert