【问题标题】:Python app engine: how to save a image?Python应用引擎:如何保存图像?
【发布时间】:2011-05-02 13:16:50
【问题描述】:

这是我从 flex 4 文件参考上传中得到的:

self.request =

    Request: POST /UPLOAD
    Accept: text/*
    Cache-Control: no-cache
    Connection: Keep-Alive
    Content-Length: 51386
    Content-Type: multipart/form-data; boundary=----------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4
    Host: localhost:8080
    User-Agent: Shockwave Flash

    ------------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4
    Content-Disposition: form-data; name="Filename"

    36823_117825034935819_100001249682611_118718_676534_n.jpg
    ------------ei4cH2gL6ae0ei4ae0gL6GI3KM7ei4
    Content-Disposition: form-data; name="Filedata"; filename="36823_117825034935819_100001249682611_118718_676534_n.jpg"
    Content-Type: application/octet-stream

    ���� [AND OTHER STRANGE CHARACTERS]

我的班级:

class Upload(webapp.RequestHandler):
    def post(self):
        content = self.request.get("Filedata")
        return "done!" 

现在,为了将该文件保存到磁盘,我在 Upload 类中缺少什么? 我在内容变量中有一些奇怪的字符(在调试中查看)。

【问题讨论】:

标签: python google-app-engine upload


【解决方案1】:

App Engine 应用程序不能:

  • 写入文件系统。应用程序必须使用 App Engine 用于存储持久数据的数据存储区。

您需要做的是向用户展示一个带有文件上传字段的表单。
提交表单后,文件被上传,Blobstore 从文件内容创建一个 blob,并返回一个对稍后检索和提供 blob 有用的 blob 键。
允许的最大对象大小为 2 GB。

这是一个工作的 sn-p,您可以按原样尝试:

#!/usr/bin/env python
#

import os
import urllib

from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class MainHandler(webapp.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        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 UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file') 
        blob_info = upload_files[0]
        self.redirect('/serve/%s' % blob_info.key())

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)

def main():
    application = webapp.WSGIApplication(
          [('/', MainHandler),
           ('/upload', UploadHandler),
           ('/serve/([^/]+)?', ServeHandler),
          ], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
  main()

EDIT1:
在您的具体情况下,您可以使用 BlobProperty(限制为 1MB)来存储您的请求:

class Photo(db.Model):
 imageblob = db.BlobProperty()

然后调整您的 webapp.RequestHandler 以保存您的请求:

class Upload(webapp.RequestHandler):
    def post(self):
        image = self.request.get("Filedata")
        photo = Photo()
        photo.imageblob = db.Blob(image) 
        photo.put()

EDIT2:
您不需要更改您的 app.yaml,只需添加一个新的处理程序并将其映射到您的 WSGI 中。 要检索存储的照片,您应该添加另一个处理程序来提供您的照片:

class DownloadImage(webapp.RequestHandler):
    def get(self):
        photo= db.get(self.request.get("photo_id"))
        if photo:
            self.response.headers['Content-Type'] = "image/jpeg"
            self.response.out.write(photo.imageblob)
        else:
            self.response.out.write("Image not available")

然后映射您的新 DownloadImage 类:

application = webapp.WSGIApplication([
    ...
    ('/i', DownloadImage),
    ...
], debug=True)

您将能够使用以下网址获取图像:

yourapp/i?photo_id = photo_key

根据要求,如果出于任何奇怪的原因您真的想使用这种 url www.mysite.com/i/photo_key.jpg 来提供图片,您可能想尝试一下:

class Download(webapp.RequestHandler):
        def get(self, photo_id):
            photo= db.get(db.Key(photo_id))
            if photo:
                self.response.headers['Content-Type'] = "image/jpeg"
                self.response.out.write(photo.imageblob)
            else:
                self.response.out.write("Image not available")

映射略有不同:

application = webapp.WSGIApplication([
        ...
        ('/i/(\d+)\.jpg', DownloadImage),
        ...
    ], debug=True)

【讨论】:

  • 谢谢! (:但是我的应用程序是用 flex 制作的,并且我使用 fileReference 来逐个上传图像。文件引用发送一个 bytearray 对象。我只需要代码来保存 bytearray 对象(即实际图像)到数据存储区。再次感谢 ;)
  • 再次感谢! :) 你知道如何设置我的 app.yaml 和 ServeHandler 以获取像“www.mysite.com/i/photo_key.jpg”这样的文件吗?
  • (ho visto k sei italiano xD) - 无论如何它不能按预期工作我的网址是:“localhost:8080/i/agt0b3R0eXN3b3JsZHIQCxIJSW1hZ2VCbG9iGIUDDA.jpg”,我只想要“agt0b3R0eXN3b3JsZHIQCxIJSW1hZ2VCbG9iGIUDDA”部分,即照片。_key |和 '/i/(\d+)\.jpg' 不起作用..
  • 让它工作!更改:r'/i/(.*)\.jpg' |然后: db.get(self.request.get(photo_id)) -> db.get(db.Key(photo_id)) 谢谢!!!
猜你喜欢
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 2015-01-17
  • 2019-05-27
  • 2010-12-03
相关资源
最近更新 更多