Question

This may come off as a bit newb-ish, but I don't really know how to approach this.

Can anyone recommend me a way of delivering and image from a flask backend, after being called by an angular $http.get call?

Brief example of what I am trying to do.

//javascript code
myApp.controller('MyCtrl', function($scope, $http){
    $http.get('/get_image/').success(function(data){
        $scope.image = data;
    });
});

#flask back end
@app.route('/get_image/', methods= ['GET', 'POST'])
def serve_image():
    image_binary = get_image_binary()   #returns a .png in raw bytes
    return image_binary

<!-- html -->
<html ng-app= "myApp">
    <div ng-controller= "MyCtrl">
        {{ image }}
    </div>
</html>

So as you can see, I am attempting to serve a raw-byte .png image from the flask backend, to the frontend.

I've tried something like this

<html>
    <img src= "/get_image/">
</html>

But the trouble is, 'get_image_binary' takes a while to run, and the page loads before the image is ready to be served. I want the image to load asyncronously to the page, only when it is ready.

Again, I am sure there are many ways to do this, probably something built into angular itself, but it is sort of difficult to phrase this into a google-able search.

Was it helpful?

Solution

Can't speak to the flask stuff, but below is some AngularJS code.

This directive won't replace the source attribute until after Angular manipulates the DOM and the browser renders (AngularJS : $evalAsync vs $timeout).

HTML:

<div ng-controller="MyController">
   <img lazy-load ll-src="http://i.imgur.com/WwPPm0p.jpg" />
</div>

JS:

angular.module('myApp', [])
.controller('MyController', function($scope) {})
.directive('lazyLoad', function($timeout) {
    return {
        restrict:'A',
        scope: {},
        link: function(scope, elem, attrs) {
            $timeout(function(){ elem.attr('src', attrs.llSrc) });
        },
    }
});

Same code in a working JSFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top