我需要将所有数据从 Django 中的表单发送到其他应用程序(通过 REST API)。问题在于转发 InMemoryUploadedFile (我从请求中捕获它)。我对构建新请求有很大的问题:文件的内容总是空的(上传的文件是空的)。我必须创建自己的 request.body builder 方法 (encode_multipart_formdata) cus 请求,我不知道为什么,无法正确执行此操作。当我调用时在这个函数内部: tmpfile.read() 我得到了空字符串,但是当我尝试更早地为 ex 执行此操作时。在 addContent() 中一切正常..
视图.py
def addContent(request):
if request.method == 'POST': # If the form has been submitted...
form = ContentForm(request.POST, request.FILES)
if form.is_valid():
data = restApiController.addContent(request.POST, request.FILES)
return HttpResponseRedirect('/content') # Redirect after POST
else:
form = ContentForm # An unbound form
return render(request, 'content/addNew.html', {'form': form, })
restApiController.py
import requests
from io import BytesIO
def addContent(requestPOST, requestFILE):
content_type, body = encode_multipart_formdata(requestPOST, requestFILE)
h = {'Content-Type': content_type}
r = requests.post(settings.CONTENTS_URL, auth=('user', 'pass'), headers=h, data=body)
def encode_multipart_formdata(fields, files):
boundary = 'ARCFormBoundaryovmtr0efdw019k9'
CRLF = '\r\n'
L = []
for (key, value) in fields.iteritems():
L.append('--' + boundary)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, value) in files.iteritems():
L.append('--' + boundary)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % ('contentFile', files['contentFile']._name))
L.append('Content-Type: %s' % get_content_type(files['contentFile']._name))
L.append('')
L.append(files['contentFile'].read())
L.append('--' + boundary + '--')
L.append('')
#body = CRLF.join(L) INSTEAD DO THIS:
s = BytesIO()
for element in L:
s.write(str(element))
s.write(CRLF)
body = s.getvalue()
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body
正文内容:
-----------------------------11286521771531197711838573892
Content-Disposition: form-data; name="name"
test
-----------------------------11286521771531197711838573892
Content-Disposition: form-data; name="language"
eng
-----------------------------11286521771531197711838573892
Content-Disposition: form-data; name="contentFile"; filename="chaos_handdrums.wav"
Content-Type: audio/x-wav
-----------------------------11286521771531197711838573892
Content-Disposition: form-data; name="type"
stream
-----------------------------11286521771531197711838573892--
在正文上下文中也应该是二进制文件的上下文,但不是..