Reputation: 2781
I am developing an application that will take HTML and images from the user and save it in a datastore. So far this part is done. How do I serve these images as resources of the HTML page when a user requests a particular one?
Upvotes: 0
Views: 106
Reputation: 882591
If you're adamant you want to keep images in the GAE datastore (not usually the best approach -- Google Cloud Storage is), you can serve them e.g with a handlers:
entry with
handlers:
- url: /img/*
- script: images.app
and in images.py
you have something like
app = webapp2.WSGIapplication('/img/(.*)', ImgHandler)
with, earlier in the same file, s/thing like:
class ImgHandler(webapp2.RequestHandler):
def get(self, img_key_urlsafe):
key = ndb.Key(urlsafe=img_key_urlsafe)
img = key.get()
self.response.headers['Content-Type'] = 'image/png'
self.response.write(img.data)
Of course, you'll have to arrange to have the images' URLs on the client side (e.g in HTML from jinja2 templates) properly prepared as
/img/some_image_key_urlsafe
and I'm assuming the images are PNG, etc (you could have the content type as one of the image entity's attributes, of course).
Unless the images are really small, this will add substantial load to your GAE app, which could be minimized by stashing the images up in Google Storage and serving them directly from there... serving them directly from datastore IS feasible (as long as they're pretty small, since a GAE entity is bounded to max 1MB!), but it's usually not optimal.
Upvotes: 3