Reputation: 2634
I'm new to the GAE (Python) and really need some help getting my head around serving images from the Datastore and accesing them within client-side Javascript.
I've been folling Google's tutorial here: Serving Dynamic Images with Google App Engine (Python)
Let's say I have the data object to store some images
class Default_tile(db.Model)
name = db.StringProperty()
image = db.BlobProperty(default=None)
Is the correct code to add an image to the above database this?:
default_tile = Default_tile()
default_tile.name = "grass"
default_tile.image = db.Blob(urlfetch.Fetch("http://www.bbc.com/grass.png").content)
default_tile.put()
No lets say I have the following code on the client side javascript:
var image = new Image();
image.onload = function() {
context.drawImage(image, 69, 50);
};
imageObj.src = ***how to I get the image, named grass, from the Datastore***
So my question is how would I get the image?
Ideally, I would like to just use imageObj.src = /images/grass
Thanks for your help.
Upvotes: 0
Views: 96
Reputation: 21835
You followed the example correctly, but you missed the part for Retrieving & Displaying Images from the same URL.
Basically you'll need a handler that will locate this image and then serve it. In your case assume that the title
in the example is name
in your case. So you will end up with a URL for retrieving images with something like this:
http://localhost:8080/image?name=grass
and this will deliver the image, so if you want to use in the client you can simply use it as
imageObj.src = '/image?name=grass'
If you're planning on storing many images and getting them from the users, then you should consider using the Blobstore API instead. It's a bit more complicated for beginners but it pays of later, since you are able to store your images (or anything else) on the Google Cloud Storage which is much cheaper.
From that example you'll be able to store and serve blobs, but you could also store the blob_info.key()
in your Model using the BlobKeyProperty
, instead of the BlobProperty
.
Having that instead of pure Datastore, you'll be able to get advantage of the get_serving_url() function that:
Returns a URL that serves the image.
This URL format allows dynamic resizing and cropping, so you don't need to store different image sizes on the server. Images are served with low latency from a highly optimized, cookieless infrastructure.
Upvotes: 1