Python应用程序引擎:如何保存图像? [英] Python app engine: how to save a image?

查看:102
本文介绍了Python应用程序引擎:如何保存图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我从flex 4文件引用上传得到的内容:

self.request =

 请求:POST / UPLOAD 
Accept:text / *
Cache-Control:no-cache
连接:保持活动
Content-Length: 51386
Content-Type:multipart / form-data; border = ---------- 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上;文件名=36823_117825034935819_100001249682611_118718_676534_n.jpg
内容类型:application / octet-stream

[和其他奇怪字符]

我的课程:

 类上传(webapp.RequestHandler ):
def post(self):
content = self.request.get(Filedata)
returndone!

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

解决方案


App Engine应用程序不能:


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


您需要什么要做的是向用户展示带有文件上传字段的表单。

表单提交后,文件将上传并且 Blobstore 根据文件内容创建一个blob,并返回一个blob关键字,用于稍后检索和提供blob 。

允许的最大对象大小为2千兆字节。



以下是您可以尝试的工作片段:


$ b $

 #!/ usr / bin / env python 


导入os
导入urllib

from google.appengine.ext从google.appengine.ext导入blobstore
从google.appengine.ext.webapp导入webapp
从google.appengine.ext导入blobstore_handlers
.webapp从google.appengine.ext.weba导入模板
pp.util import run_wsgi_app
$ b class MainHandler(webapp.RequestHandler):
def get(self):$ b $ upload_url = blobstore.create_upload_url('/ upload')
self.response.out.write('< html>< body>')
self.response.out.write('< form action =%smethod =POSTenctype =multipart / form-data>'%upload_url)
self.response.out.write(上传文件:< input type =filename =file>< br> < input type =submit
name =submitvalue =Submit> < / body>< / html>)

class UploadHandler = 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),
(' (上传),UploadHandler),
('/ serve /([^ /] +)',ServeHandler),
],debug = True)
run_wsgi_app(应用程序)

if __name__ =='__main__':
main()

< EDIT1:

在你的具体情况下,你可以请 BlobProperty (限于1MB)存储您的请求:

  class图片(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()

编辑2:

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

  class DownloadImage(webapp.RequestHandler) :
def get(self):
photo = db.get(self.request.get(photo_id))
如果照片:
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 

根据要求,如果出于任何奇怪的原因,您确实想使用这种类型的网址 www.mysite.com/i/photo_ke y.jpg ,你可能想尝试一下:

  class Download(webapp.RequestHandler) :
def get(self,photo_id):
photo = db.get(db.Key(photo_id))
如果照片:
self.response.headers ['Content-输入'] =image / jpeg
self.response.out.write(photo.imageblob)
else:
self.response.out.write(Image not available)

有一个稍微不同的映射:

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


This is what I got from flex 4 file reference upload:

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]

My class:

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

Now what I'm missing in the Upload class in order to save that file to disk? i have in the content var some strange characters (viewing in debug).

解决方案

An App Engine application cannot:

  • write to the filesystem. Applications must use the App Engine datastore for storing persistent data.

What you need to do is presenting a form with a file upload field to the user.
When the form is submitted, the file is uploaded and the Blobstore creates a blob from the file's contents and returns a blob key useful to retrieve and serve the blob later.
The maximum object size permitted is 2 gigabytes.

Here is a working snippet that you can try as is:

#!/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:
in your specific case you could use a BlobProperty (limited to 1MB) to store your request:

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

then adapt your webapp.RequestHandler to save your request:

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

EDIT2:
You don't need to change your app.yaml, just add a new handler and map it in your WSGI. To retrieve the stored photo you should add another handler to serve your photos:

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")

then map your new DownloadImage class:

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

You would be able to get images with a url like:

yourapp/i?photo_id = photo_key

As requested, if for any odd reason you really want to serve your images using this kind of url www.mysite.com/i/photo_key.jpg , you may want to try with this:

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")

with a slightly different mapping:

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

这篇关于Python应用程序引擎:如何保存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆