使用Flask(python)从GAE数据存储区提供图像

时间:2013-08-05 14:55:04

标签: google-app-engine python-2.7 flask google-cloud-datastore blobstore

我想避免使用GAE中的Webapp ,因此我使用此代码将图片上传到Blobstore(代码片段来自:http://flask.pocoo.org/mailinglist/archive/2011/1/8/app-engine-blobstore/#7fd7aa9a5c82a6d2bf78ccd25084ac3b

@app.route("/upload", methods=['POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        header = f.headers['Content-Type']
        parsed_header = parse_options_header(header)
        blob_key = parsed_header[1]['blob-key']
        return blob_key

它返回它看起来确实是一个Blobkey,它是这样的:

  

2I9oX6J0U5nBCVw8kEndpw ==

然后我尝试使用以下代码显示最近存储的Blob图像:

@app.route("/testimgdisplay")
def test_img_display():
    response = make_response(db.get("2I9oX6J0U5nBCVw8kEndpw=="))
    response.headers['Content-Type'] = 'image/png'
    return response

可悲的是这部分不起作用,我收到以下错误:

BadKeyError: Invalid string key 2I9oX6J0U5nBCVw8kEndpw==

你们之前是否遇到过此错误?看起来Blobkey格式正确,我找不到线索。

2 个答案:

答案 0 :(得分:8)

在收到Blob的电话中有一个简单的错误,我写道:

db.get("2I9oX6J0U5nBCVw8kEndpw==")

而是正确的电话:

blobstore.get("2I9oX6J0U5nBCVw8kEndpw==")

对于那些在不使用Webapp的情况下通过GAE Blobstore和Flask寻找完整的上传/服务图片的人,以下是完整的代码:

渲染上传表单的模板:

@app.route("/upload")
def upload():
    uploadUri = blobstore.create_upload_url('/submit')
    return render_template('upload.html', uploadUri=uploadUri)

将uploadUri放在表单路径(html)中:

<form action="{{ uploadUri }}" method="POST" enctype="multipart/form-data">

这是处理图像上传的功能(我出于实际原因返回blob_key,用模板替换它):

@app.route("/submit", methods=['POST'])
def submit():
    if request.method == 'POST':
        f = request.files['file']
        header = f.headers['Content-Type']
        parsed_header = parse_options_header(header)
        blob_key = parsed_header[1]['blob-key']
        return blob_key

现在说你用这样的路径为你的图像提供服务:

  

/ IMG /映像文件名称

然后你的图像服务功能是:

@app.route("/img/<bkey>")
def img(bkey):
    blob_info = blobstore.get(bkey)
    response = make_response(blob_info.open().read())
    response.headers['Content-Type'] = blob_info.content_type
    return response

最后,无论您需要在模板中显示图像,只需输入代码:

<img src="/img/{{ bkey }} />

答案 1 :(得分:0)

我不认为Flask在提供Blobstore图像方面比Webapp更好或更差,因为他们都使用Blobstore API来Serving a Blob

你所谓的Blobkey只是一个字符串,需要转换为一个键(这里称为resource):

from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
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)
相关问题