Google App Engine:使用webapp2上传和提供blob

时间:2015-06-20 15:53:01

标签: python python-2.7 google-app-engine webapp2

我尝试按照本教程上传并将图像作为blob提供: https://cloud.google.com/appengine/docs/python/blobstore/

这是我的main.py文件:

import webapp2

from google.appengine.api import users
from google.appengine.ext import blobstore
from google.appengine.ext import ndb
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp.util import run_wsgi_app

# A custom datastore model for associating users with uploaded files.
class UserPhoto(ndb.Model):
  user = ndb.StringProperty()
  # blob_key = blobstore.BlobReferenceProperty()
  blob_key = ndb.BlobKeyProperty()


class PhotoUploadFormHandler(webapp2.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload_photo')
        # The method must be "POST" and enctype must be set to "multipart/form-data".
        self.response.out.write('<html><body>')
        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write('''Upload File: <input type="file" name="file"><br> <input type="submit"
            name="submit" value="Submit"> </form></body></html>''')

class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        try:
            upload = self.get_uploads()[0]
            user_photo = UserPhoto(user=users.get_current_user().user_id(),
                                   blob_key=upload.key())
            user_photo.put()

            self.redirect('/view_photo/%s' % upload.key())

        except:
            self.redirect('/upload_failure.html')

class ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, photo_key):
        if not blobstore.get(photo_key):
            self.error(404)
        else:
            self.send_blob(photo_key)


app = webapp2.WSGIApplication([('/', PhotoUploadFormHandler),
                               ('/upload_photo', PhotoUploadHandler),
                               ('/view_photo/([^/]+)?', ViewPhotoHandler),
                              ], debug=True)

当我尝试运行此应用程序时,我确实获得了上传文件&#39;选项。当我选择要上传并提交表单的文件时,应用程序会被重定向到&#39; /upload_failure.html'我收到404 Resource not found错误。这是我的数据存储区的样子:

代码似乎有什么问题?图像文件显然存储在数据存储区中。但是,为什么应用程序无法提供图像?

0 个答案:

没有答案