topless
1/26/2016 - 10:06 PM

Flask example to upload to with google appengine blobstore api.

Flask example to upload to with google appengine blobstore api.

# coding: utf-8

from __future__ import absolute_import

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

import flask
from flask.ext import restful

import json
import config
import model

from api import helpers
from main import api_v1
import logging


# NOTE: https://cloud.google.com/appengine/docs/python/blobstore/

"""The model
class Recording(model.Base):
  blob_key = ndb.BlobKeyProperty()

  FIELDS = {
    'blob_key': fields.BlobKey,
  }
"""


@api_v1.resource('/run/<string:run_key>/recording/', endpoint='api.recording')
class RecordingAPI(restful.Resource):
  def post(self, run_key):
    data = flask.request.get_json()
    recording_db = model.Recording()
    recording_db.put()
    blob_key = create_file(recording_db.key, data)
    recording_db.blob_key = ndb.BlobKey(blob_key)
    recording_db.put()
    return helpers.make_response(recording_db, model.Recording.FIELDS)


def create_file(key, data):
  # Create a GCS file with GCS client.
  filename = "/%s/%s" % (config.CONFIG_DB.bucket_name, key.urlsafe())
  with gcs.open(filename, 'w', content_type='application/json') as f:
    f.write(json.dumps(data))

  # Blobstore API requires extra /gs to distinguish against blobstore files.
  blobstore_filename = '/gs' + filename
  return blobstore.create_gs_key(blobstore_filename)