在appengine python中使用multipart / form-data发送请求不起作用 [英] Post request with multipart/form-data in appengine python not working

查看:283
本文介绍了在appengine python中使用multipart / form-data发送请求不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从appengine应用程序发送多部分发布请求到位于dotcloud上的外部(django)api。该请求包含一些文本和文件(pdf),并使用以下代码发送:

I'm attempting to send a multipart post request from an appengine app to an external (django) api hosted on dotcloud. The request includes some text and a file (pdf) and is sent using the following code

from google.appengine.api import urlfetch
from poster.encode import multipart_encode
from libs.poster.streaminghttp import register_openers

register_openers()
file_data = self.request.POST['file_to_upload']
the_file = file_data
send_url = "http://127.0.0.1:8000/"
values = {
          'user_id' : '12341234',
          'the_file' : the_file
          }

data, headers = multipart_encode(values)
headers['User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
data = str().join(data)
result = urlfetch.fetch(url=send_url, payload=data, method=urlfetch.POST, headers=headers)
logging.info(result.content)

当此方法运行时,Appengine会发出以下警告(我不知道是否与我的问题相关)

When this method runs Appengine gives the following warning (I'm not sure if it's related to my issue)

Stripped prohibited headers from URLFetch request: ['Content-Length']

Django通过以下错误

And Django sends through the following error

<class 'django.utils.datastructures.MultiValueDictKeyError'>"Key 'the_file' not found in <MultiValueDict: {}>"

django代码很简单,当我使用邮递员chrome扩展来发送文件时,它的工作原理/ p>

The django code is pretty simple and works when I use the postman chrome extension to send a file.

@csrf_exempt
def index(request):
    try:
        user_id = request.POST["user_id"]
        the_file = request.FILES["the_file"]
        return HttpResponse("OK")
    except:
        return HttpResponse(sys.exc_info())

如果我添加

print request.POST.keys()

我得到一个包含user_id和the_file的字典表示该文件未作为文件发送。如果我对文件做同样的事情,即

I get a dictionary containing user_id and the_file indicating that the file is not being sent as a file. if I do the same for FILES i.e.

print request.FILES.keys()    

我得到空列表[]。

我已经改变了我的问题来实现someone1的建议,但是这仍然失败。我还包括Glenn发送的链接推荐的标题,但没有喜悦。

I've changed my question to implement the suggestion of someone1 however this still fails. I also included the headers addition recommended by the link Glenn sent, but no joy.

我也尝试发送the_file作为

I've also tried sending the_file as variations of

the_file = file_data.file
the_file = file_data.file.read()

但我收到相同的错误。

我还试过编辑我的django应用程序到

I've also tried editing my django app to

the_file = request.POST["the_file"]

但是当我尝试保存文件本地与

However when I try to save the file locally with

path = default_storage.save(file_location, ContentFile(the_file.read()))

它失败与

<type 'exceptions.AttributeError'>'unicode' object has no attribute 'read'<traceback object at 0x101f10098>

同样,如果我尝试访问the_file.file(我可以在我的appengine应用程序中访问),它告诉我

similarly if I try access the_file.file (as I can access in my appengine app) it tells me

<type 'exceptions.AttributeError'>'unicode' object has no attribute 'file'<traceback object at 0x101f06d40>


推荐答案

这是我在本地测试的一些代码,技巧(我使用了不同于webapp2的处理程序,但是尝试将其修改为webapp2。您还需要在这里找到的海报lib http://atlee.ca/software/poster/ ):

Here is some code I tested locally that should do the trick (I used a different handler than webapp2 but tried to modify it to webapp2. You'll also need the poster lib found here http://atlee.ca/software/poster/):

在GAE的POST处理程序中:

In your POST handler on GAE:

from google.appengine.api import urlfetch
from poster.encode import multipart_encode
payload = {}
payload['test_file'] = self.request.POST['test_file']
payload['user_id'] = self.request.POST['user_id']
to_post = multipart_encode(payload)
send_url = "http://127.0.0.1:8000/"
result = urlfetch.fetch(url=send_url, payload="".join(to_post[0]), method=urlfetch.POST, headers=to_post[1])
logging.info(result.content)

确保您的HTML表单包含 method =POSTenctype =multipart / for间数据。希望这有帮助!

Make sure your HTML form contains method="POST" enctype="multipart/form-data". Hope this helps!

编辑:
我尝试使用webapp2处理程序,并意识到文件的服务方式与框架我用来测试作品(KAY)。这里是应该做的伎俩的更新代码(在生产中测试):

I tried using the webapp2 handler and realized the way files are served are different than how the framework I used to test with works (KAY). Here is updated code that should do the trick (tested on production):

import webapp2
from google.appengine.api import urlfetch
from poster.encode import multipart_encode, MultipartParam

class UploadTest(webapp2.RequestHandler):
  def post(self): 
    payload = {}
    file_data = self.request.POST['test_file']
    payload['test_file'] = MultipartParam('test_file', filename=file_data.filename,
                                          filetype=file_data.type,
                                          fileobj=file_data.file)
    payload['name'] = self.request.POST['name']
    data,headers= multipart_encode(payload)
    send_url = "http://127.0.0.1:8000/"
    t = urlfetch.fetch(url=send_url, payload="".join(data), method=urlfetch.POST, headers=headers)
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write(t.content)
  def get(self):
    self.response.out.write("""
    <html>
        <head>
            <title>File Upload Test</title>
        </head>
        <body>
            <form action="" method="POST" enctype="multipart/form-data">
                <input type="text" name="name" />
                <input type="file" name="test_file" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>""")

这篇关于在appengine python中使用multipart / form-data发送请求不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆