google-app-engine - Google App Engine - 从 Python 代码将文件上传到 blobstore 时出错

标签 google-app-engine python-2.7 blobstore urlfetch

我正在开发一个应用程序来处理发送到我邮箱的电子邮件。我已修改我的邮件设置以将收到的邮件转发到 myapp。到达 myapp 的邮件将被路由到将在其中处理的处理程序脚本(“handle_incoming_email.py”)。我的 app.yaml 文件如下所示

应用.yaml

application: myapp
version: 1-1
runtime: python27
api_version: 1
threadsafe: false
default_expiration: "360d"

handlers:
- url: /_ah/mail/.+
  script: myapp/utils/handle_incoming_email.py

邮件处理脚本如下所示

handle_incoming_email.py

import logging
import urllib
import base64
import traceback
from google.appengine.ext import webapp
from google.appengine.ext import blobstore
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler


class ReceiveEmail(InboundMailHandler):

    def receive(self, message):
        try:
            for filename, filecontents in message.attachments:
                if filecontents.encoding:
                    # data = filecontents
                    data = filecontents.decode()
                    # data = filecontents.payload
                    # data = filecontents.payload.decode()
                    # data = base64.b64decode(filecontents.decode())
                    # data = base64.b64decode(filecontents.payload)
                    # data = base64.b64decode(filecontents.payload.decode())

                upload_url = blobstore.create_upload_url('http://myapp.appspot.com/settings/saveItem/')
                form_fields = {'field_name': data}
                form_data = urllib.urlencode(form_fields)
                result = urlfetch.fetch(url=upload_url,
                                        payload=form_data,
                                        method=urlfetch.POST,
                                        headers={'Content-Type': 'application/x-www-form-urlencoded'})
                logging.info(result)
        except Exception, e:
            traceback.print_exc()

application = webapp.WSGIApplication([ReceiveEmail.mapping()], debug=True)


def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()

我的要求是创建一个对应于每个带附件的邮件的实体。为此,我需要解析邮件中的附件并将其上传到 blobstore。但是,当我尝试将附件上传到 blobstore 时,出现以下错误:

此 URL 不接受请求的内容类型。

正如您在“handle_incoming_email.py”中的注释代码中看到的那样,我尝试了不同的方法(反复试验)来使数据正确,但无济于事。

有人可以指导我解决这个问题吗!

谢谢!!!

最佳答案

我认为此代码示例可以解决您的问题。您可能只需要使用此代码中的 encode_multipart_formdata 函数。并且不要忘记正确设置内容类型。

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

关于google-app-engine - Google App Engine - 从 Python 代码将文件上传到 blobstore 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17294507/

相关文章:

rest - 使用 go API 在 blobstore 上上传文件

java - 将特定文本文件上传到 blobstore 会引发异常

python - 什么是最好的 Google App Engine blobstore 工作流程?

java - 在 Eclipse 中升级到新的云工具插件后,本地服务器显示 "stopping, synchronized."

google-app-engine - Google App 引擎看不到我的 CSS 文件

google-app-engine - 为什么给定类型的 ID 在 Google Cloud Datastore 中不唯一?

python - 在字符串中的每个字符前后放置一个符号

python-2.7 - 将测试集分为子组,然后分别对每个子组进行预测

java - Eclipse 在我的 web.xml 中报告问题,但处理得很好

python - Gridspec 范围错误