How to stream images to the browser with Django
Question: Forgive me if I am using these terms incorrectly, I'm pretty new to the
concept of streaming and I haven't found many resources in Googling that
talked about the best use cases for streaming.

What I have right now:

Browser makes a requests for an image to a Django endpoint

    
    
    var img = new Image();
    img.src = 'http://www.example.com/api/images/51234/
    img.onload = function() {
        $('#my-img').attr('src', this.src);
    }
    

Django turns around makes another request to a service for an image

    
    
    import requests
    
    def get_image(request, img_id):
        response = requests.get("http://api.myexample.net/album/123/img/{0}".format(img_id))
    
        return HttpResponse(res.content, mimetype="image/jpeg")
    

My understanding of this process is that Django will read all of the binary
information for this image into memory before turning around to deliver the
response to the browser. Is there a way I can stream it directly down to the
browser rather than waiting for the image to be delivered completely to
Python?

I have read the documentation for the
[StreamingHTTPResponse](https://docs.djangoproject.com/en/1.9/ref/request-
response/#django.http.StreamingHttpResponse) class but all the examples show
simply reading a file off of the server's disk and passing it to a
StreamingHTTPResponse, not getting it from another service.


Answer: You dont have to get download image content using `requests.get`. Lets say:

    
    
    def viewFunc(request):
        image_url = 'some.image.url.jpg'
    

you can pass the url to your html file simply via context.

    
    
    return render(request, 'some_html.html', {'image_url':image_url})
    

Then in html use like :

    
    
    <img src="{{image_url}}" id="image_id">
    

Or if you are using ajax:

    
    
    return HttpResponse(json.dumps({'image_url':image_url}))
    

Then in html:

    
    
    success : function(response){
        var image_url = response.image_url;
        $('#image_id').attr('src',image_url);
    }
    

This way django will only pass the url to image view and the image will render
from frontend. There is no need to download image using requests.get since all
the browsers are capable of generating image from image tag.

