在没有Files API的情况下保存来自urlfetch的图像

时间:2013-06-20 11:02:16

标签: google-app-engine blobstore

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

当删除Files API时,是否有其他方法可以直接将文件写入blobstore?

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

1 个答案:

答案 0 :(得分:2)

这是一个解决我问题的例子。现在我们可以通过编程方式上传文件,避免使用已弃用的文件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