user2609060
user2609060

Reputation: 63

Doing Image transforms inside an UploadHandler and saving it to the Blobstore

I have a page on GAE written in Python that (1)uploads a jpg to the the blobstore. That part works. I need to now do an (2)I'm Feeling Lucky Image transform, then (3)store it as another blob in the blobstore. Ideally, I'd like to do (1), (2), and (3) in the same Upload Handler.

I've followed the code here, but it only does (1), and (2). https://developers.google.com/appengine/docs/python/images/#Python_Transforming_images_from_the_Blobstore

I've looked through SO and the closest I could find is this: Storing Filtered images on the blobstore in GAE

It saves the transform to a file (using the Files API) then uploads the file to the blobstore. However, it uses the Files api, and according to the following, the Files API is deprecated. https://developers.google.com/appengine/docs/python/blobstore/#Python_Writing_files_to_the_Blobstore

In my Model, I have a BlobKeyProperty that stores a reference to the image in the blobstore

class ImageModel(ndb.Model):
   imagetoserve =  ndb.BlobKeyProperty(indexed=False)

Here's the Upload Handler code so far:

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

upload_files = self.get_uploads('imgfile')  # 'file' is file upload field in the form
blob_info = upload_files[0]

imgtmp = images.Image(blob_info)
imgtmp.im_feeling_lucky()
img = ImageModel()
img.imagetoserve = imgtmp
img.put()

My problem is on this line:

img.imagetoserve = imgtmp

The model is a blobkeyproperty but I'm feeding it an image, obviously resulting in a type mismatch kind of error. How do I do the step of uploading the transformed imgtmp to the blobstore, capturing the blobkey, and saving the reference to my model?

Upvotes: 2

Views: 264

Answers (1)

someone1
someone1

Reputation: 3570

Read the Blobstore API Documentation

Unfortunately, you would have traditionally done this through the Files API, but since they are deprecating that in favor of using GCS, you can do the following (you can fill in the missing pieces): (From this example)

import cloudstorage as gcs
from google.appengine.ext import blobstore

class ImageModel(ndb.Model):
    image_filename = ndb.StringProperty(indexed=False)

    @property
    def imagetoserve(self):
        return blobstore.create_gs_key(self.image_filename)

BUCKET = "bucket_to_store_image\\"

with gcs.open(BUCKET + blob_info.filename, 'w', content_type='image/png') as f:
    f.write(imgtmp.execute_transforms())

img = ImageModel()
img.image_filename = BUCKET + blob_info.filename
img.put()

Upvotes: 1

Related Questions