Google App Engine:从数据存储中检索图像

时间:2014-03-14 17:43:59

标签: python google-app-engine blob

我的图片存储在Google应用引擎数据存储区中。我想检索它们并在我的应用程序中显示它们。这是我的应用程序的代码:

main.py

class FileUpload(Handler):
    def post(self):
        file_upload = self.request.POST.get("file", None)
        file_name = file_upload.filename
        image = Images(id=file_name, file_name=file_name, blob=file_upload.file.read())
        image.put()

        self.response.headers[b'Content-Type'] = mimetypes.guess_type(image.file_name)[0]
        self.response.write(image.blob)

class ImgServe(Handler):
    def get(self, resource):
        image = ndb.Key('Images', resource).get()
        self.response.headers[b'Content-Type'] = mimetypes.guess_type(image.file_name)[0]
        self.response.write(image.blob)            

class Blob(Handler):
    def get(self):
        self.render("blob.html")

class Template(Handler):
    def get(self):
        self.render('template.html')


app = webapp2.WSGIApplication([('/', MainPage),
                                ('/signup', Register),
                                ('/login', Login),
                                ('/logout', Logout),
                                ('/mp', MP),
                                (r'/file_upload', FileUpload),
                                ('/blob', Blob),
                                (r'/img_serve/<resource:(.*)>', ImgServe),
                                ('/template', Template)], debug=True)

blob.html

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Image Upload</title>
</head>
<body>
<form action="/file_upload" enctype="multipart/form-data" method="post">
    <div><input type="file" name="file"/></div>
    <div><input type="submit" value="Upload"></div>
</form>
</body>
</html>

template.html

<html>
<head>
    <title>Template</title>
</head>
<body>
    <img src="/img_serve/evs.jpeg" /> 
</body>
</html>

以下是我的数据库的屏幕截图:

enter image description here

但是,这是我在template.html上获得的输出:

enter image description here

我期待'evs.jpeg'显示在template.html上。我的代码似乎有什么问题?

1 个答案:

答案 0 :(得分:0)

您没有义务自己提供图片。 Google可以为您完成这项工作:

请参阅:https://developers.google.com/appengine/docs/python/images/functions

get_serving_url(blob_key,size = None,crop = False,secure_url = None)

您只需传递已存储的blob_key,即可获取服务网址,以便在HTML模板中使用。

或者,您可以按照服务blob的文档:

见这里:https://developers.google.com/appengine/docs/python/blobstore/#Python_Complete_sample_application

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
    resource = str(urllib.unquote(resource))
    blob_info = blobstore.BlobInfo.get(resource)
    self.send_blob(blob_info)

也可以通过传入一个字符串来覆盖文件名:

self.send_blob(blob_info,save_as='evs.jpg')