venky venky - 1 year ago 66
HTML Question

Image which is stored as a blob in Datastore in a html page

I am trying to make a Web Application based on Google App Engine in python. A part of it deals with displaying the poster of Movie hosted at IMDb. I have the link to the poster. For ex.

Then I tried to put it in an HTML page as:

<a href="">
<img src="">

See the example here :

The image isn;t shown and on clicking it, a page opens saying:

Referral Denied

You don't have permission to access "" on this server.

Reference #24.84d81002.1393249598.981ca7

On going through this question, I came to know that IMDb does not allow referrals to any other sites. The solution was to get the image yourself, save it and then serve it yourself.
For doing that, I followed this link.

I made a datastore object storing various informations of the movie as well as the poster which was fetched using urlfetch api. relevant parts of the code are

from google.appengine.ext import db
from google.appengine.api import urlfetch

class Movie(db.Model):
title = db.StringProperty()
poster = db.BlobProperty(default=None)

coverurl = ""
movie = Movie()
posterimg = urlfetch.fetch(coverurl).content
movie.cover = db.Blob(posterimg)

Now, for rendering the html page, I got the movie object from datastore as

m = Movie.gql("WHERE title = :1", title).get()
img = m.posterimg

and the html page was rendered as

imghtml = ' <img src="' + img + '"> </a>'

An error was expected and was recieved as:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

What is the way out of this?
How can I include an Image which is stored as a blob in Datastore in a html image?

Ron Ron
Answer Source

upload image to blobstore using the app engine helpers, get the serving_url in the same handler, save the serving_url with your image object, refer to the image url in your html template


from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api.images import get_serving_url

class Handler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        img = MyImageObject()
        img.image_name = blob_info.filename
        img.image_url = get_serving_url(blob_info.key())

then in the template

<img src="{{img.image_url}}">

to get original size of image you will need to append =s0 to end of url, append =sXX to resize, see "URL Modifications" section here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download