我正在尝试将来自 appengine 应用程序的多部分发布请求发送到托管在 dotcloud 上的外部(django)api。该请求包括一些文本和一个文件 (pdf),并使用以下代码发送
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 会给出以下警告(我不确定它是否与我的问题有关)
Stripped prohibited headers from URLFetch request: ['Content-Length']
并且 Django 通过以下错误发送
<class 'django.utils.datastructures.MultiValueDictKeyError'>"Key 'the_file' not found in <MultiValueDict: {}>"
django 代码非常简单,当我使用邮递员 chrome 扩展程序发送文件时可以工作。
@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 的字典,表明该文件没有作为文件发送。如果我对文件做同样的事情,即
print request.FILES.keys()
我得到一个空列表[]。
编辑1:
我已经改变了我的问题以实施某人的建议,但这仍然失败。我还包括格伦发送的链接推荐的标题添加,但不高兴。
编辑2:
我也尝试将 the_file 作为变体发送
the_file = file_data.file
the_file = file_data.file.read()
但我得到同样的错误。
编辑 3:
我也尝试将我的 django 应用程序编辑为
the_file = request.POST["the_file"]
但是,当我尝试在本地保存文件时
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 应用程序中访问)它会告诉我
<type 'exceptions.AttributeError'>'unicode' object has no attribute 'file'<traceback object at 0x101f06d40>