【问题标题】:Save image from urlfetch without Files API从没有文件 API 的 urlfetch 保存图像
【发布时间】:2013-06-20 11:02:16
【问题描述】:

允许实用地将文件写入 blobstore 的 API 现在已弃用,将来将被删除。但我正在使用这个 API 来保存来自外部服务的用户图片。我不能使用上传处理程序来执行此操作。

当 Files API 将被删除时,是否有任何替代方法可以将文件直接写入 blobstore?

https://developers.google.com/appengine/docs/python/blobstore/#Writing_Files_to_the_Blobstore

【问题讨论】:

  • 红框中的那张纸条让你感到困惑吗?不推荐写入 blobstore,您应该改为写入 Cloud Storage。
  • 我不想使用额外的库。 (GCS)
  • 你别无选择。

标签: google-app-engine blobstore


【解决方案1】:

这是一个解决我的问题的例子。现在我们可以通过编程方式上传文件,避免弃用 Files API。

class BlobstoreUpload(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    upload_files = self.get_uploads('file')
    blob_info = upload_files[0]
    return self.response.write(blob_info.key())

  @classmethod
  def encode_multipart_formdata(cls, fields, files, mimetype='image/png'):
    """
    Args:
      fields: A sequence of (name, value) elements for regular form fields.
      files: A sequence of (name, filename, value) elements for data to be
        uploaded as files.

    Returns:
      A sequence of (content_type, body) ready for urlfetch.
    """
    boundary = 'paLp12Buasdasd40tcxAp97curasdaSt40bqweastfarcUNIQUE_STRING'
    crlf = '\r\n'
    line = []
    for (key, value) in fields:
      line.append('--' + boundary)
      line.append('Content-Disposition: form-data; name="%s"' % key)
      line.append('')
      line.append(value)
    for (key, filename, value) in files:
      line.append('--' + boundary)
      line.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
      line.append('Content-Type: %s' % mimetype)
      line.append('')
      line.append(value)
    line.append('--%s--' % boundary)
    line.append('')
    body = crlf.join(line)
    content_type = 'multipart/form-data; boundary=%s' % boundary
    return content_type, body


class UserProfile(webapp2.RequestHandler):
  def post(self):
    picture = self.request.POST.get('picture')

    # Write new picture to blob
    content_type, body = BlobstoreUpload.encode_multipart_formdata(
      [], [('file', name, image)])
    response = urlfetch.fetch(
      url=blobstore.create_upload_url(self.uri_for('blobstore-upload')),
      payload=body,
      method=urlfetch.POST,
      headers={'Content-Type': content_type},
      deadline=30
    )
    blob_key = response.content

【讨论】:

  • 感谢您的示例代码。是否可以分块发布 blob?
  • @voscausa 为什么需要这个?但我认为可以将文件“拆分”成块并将它们中的每一个放在不同的 blob 中。或者你想把 chunk1 他们把 chunk2 放到单个 blob 中?
  • 我需要读取、缓冲和发布/上传大块。现在我使用文件 API 和任务编写 blob 块。
猜你喜欢
  • 1970-01-01
  • 2016-01-15
  • 2017-07-19
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
相关资源
最近更新 更多