【问题标题】:Serve image from GAE datastore with Flask (python)使用 Flask (python) 从 GAE 数据存储中提供图像
【发布时间】:2013-08-06 08:14:14
【问题描述】:

我想避免使用 GAE 中的 Webapp,所以我使用此代码将图像上传到 Blobstore(代码 sn-p 来自: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 的格式似乎很好,我找不到线索。

【问题讨论】:

  • 我认为问题在于你得到的 blobkey 似乎是 base64 编码的。
  • 谢谢,它把我推向了正确的方向;)

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


【解决方案1】:

在获取 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 }} />

【讨论】:

    【解决方案2】:

    我不认为 Flask 在提供 Blobstore 图像方面比 Webapp 更好或更差,因为它们都使用 Blobstore API for 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2011-04-30
      • 2014-06-20
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      相关资源
      最近更新 更多