6

我想避免使用 GAE 中的 Webapp,所以我使用此代码将图像上传到 Blobstore(代码片段来自: http: //flask.pocoo.org/mailinglist/archive/2011/1/8/app-引擎-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 格式正确,我找不到线索。

4

2 回答 2

8

获取 Blob 的调用有一个简单的错误,我写道:

db.get("2I9oX6J0U5nBCVw8kEndpw==")

而正确的电话是:

blobstore.get("2I9oX6J0U5nBCVw8kEndpw==")

对于那些通过 GAE Blobstore 和 Flask 而不使用 Webapp 来寻找完整的上传/服务图像的人,这里是完整的代码:

渲染上传表单的模板:

@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 }} />
于 2013-08-06T06:51:42.387 回答
0

我不认为 Flask 在提供 Blobstore 图像方面比 Webapp 更好或更差,因为它们都使用 Blobstore API 来提供 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)
于 2013-08-05T17:22:37.203 回答