2
votes

I wrote a simple webapp using google app engine in python that allows users to upload images and have it stored somewhere (for now I'm just using the blob store based on the tutorials).

Now I want to send the images to google cloud storage, but am not sure how to do this. They provide two modes when opening a file: "a" and "r". Neither of them, to my knowledge, are for binary streams.

How can I send an image to google cloud storage? Code snippets or references would be nice. I am planning to send small audio samples as well, and other binary data.

Also, how can I delete the image if a user wishes to delete it? There doesn't seem to be a delete method available.

2

2 Answers

4
votes

Here's a simple upload handler that will write the blob that was uploaded to bigstore. Note you will need to have added your app's service account to the team account that is managing the bigstore bucket.

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    upload_files = self.get_uploads('file')
    blob_info = upload_files[0]
    in_file_name = files.blobstore.get_file_name(blob_info.key())
    infile = files.open(in_file_name)
    out_file_name = '/gs/mybucket/' + blob_info.filename
    outfile = files.gs.create(out_file_name,
                              mime_type = blob_info.content_type)

    f = files.open(outfile, 'a')
    chunkSize = 1024 * 1024
    try:
      data = infile.read(chunkSize)
      while data:
        f.write(data)
        data = infile.read(chunkSize)
    finally:
      infile.close()
      f.close()

    files.finalize(outfile)
2
votes

There isn't a difference between a binary stream and a text stream in cloud storage. You just write strings (or byte strings) to the file opened in "a" mode. Follow the instructions here.

Also, if you are serving images from the blobstore, you are probably better off using get_serving_url() from here, although that depends on your application.