Andy
Andy

Reputation: 201

How can I serve an image from the blobstore to a python template in Google App Engine?

{% for result in results %}

{{ result.photo }}

{% endif %}

This clearly won't work, but I can't find any info for how to upload a photo. On the admin console, I can see that I have successfully uploaded the image to the blobstore, now how can I send it as to my webapp template?

I can show the description doing this.

{% for result in results %}

{{ result.description }}

{% endif %}

But I don't know how to get GAE to read the image file as an image.

Any help would be greatly appreciated. Thanks everyone!

Upvotes: 0

Views: 358

Answers (2)

Adam Crossland
Adam Crossland

Reputation: 14213

You should have an <img> tag in your template that has a src attribute that contains a URL that is served by your application and delivers the data for the image. For example, let's say that you store images in a model called Image:

class Image(db.Model):
    filename = db.StringProperty()  # The name of the uploaded image
    mime_type = db.StringProperty() # The mime type.
    content = db.BlobProperty()     # The bytes of the image

    def load(id):
        # Load an entity from the database using the id. Left as an
        # exercise...

    def link_id_for(self):
        "Returns an id that uniquely identifies the image"
        return self.key().id()

In the controller/request handler code that renders the page that contains the image, you would pass the id that is returned by link_id_for to the template, and the template would have your image tag, something like this:

<img src="/images/show/{{image_id}}">

You would have a request handler that handles requests to /images/show/id. You would use id to get the Image entity out of the datastore and the send it back in the response, something like this:

found_image = Image.load(id)

response.headers['Content-Type'] = str(found_image.mime_type)
response.out.write(found_image.content)

Obviously, you'd have to adapt the particulars of the code to your current application structure and conventions, but that's the heart of it: use an img tag with a src that points at your application; your application includes a request handler the delivers the bytes and a Content-Type header.

Upvotes: 2

specialscope
specialscope

Reputation: 4218

I have written a tutorial on this topic. Read it and if you have any specific problems post here. http://verysimplescripts.blogspot.com/

Upvotes: 2

Related Questions