使用werkzeug

时间:2017-05-07 03:19:30

标签: python multipart form-data werkzeug boundary

我有一个从http POST保存的文件,我想用werkzeug parse_form_data()使用Python解析。请注意,我不是通过请求获取它,而是通过文件获取它。由于其他原因,我无法直接从烧瓶请求获取文件。由于我一直在使用Flask,我尝试使用werkzeug来做到这一点。我以为我遇到了与无关连字符的边界问题' - ',但我正在修改以下测试文件中的非常简单的格式:

这是文件系统上的文件(myinputfile):

--806243354728155036129379
Content-Disposition: form-data; name="myfile"; filename="text.py"
Content-Type: application/octet-stream

some text in a file

--806243354728155036129379
Content-Disposition: form-data; name="field1"

abcde
--806243354728155036129379
Content-Disposition: form-data; name="field2"
123456678
--806243354728155036129379--

这是我使用的代码:

from werkzeug import parse_form_data
import io

inputfile = 'myinputfile'
content_type = 'Content-Type: multipart/form-data; boundary=806243354728155036129379'


environ = {
    'wsgi.input': io.open(inputfile, 'rb'),
    'CONTENT_LENGTH': '',
    'CONTENT_TYPE': content_type,
    'REQUEST_METHOD': 'POST'}

stream, form, files = parse_form_data(environ, silent=False)

我一直收到这个错误:

File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 92, in parse_form_data
cls, silent).parse_from_environ(environ)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 171, in parse_from_environ
content_length, options)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 195, in parse
content_length, options)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 100, in wrapper
return f(self, stream, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 212, in _parse_multipart
form, files = parser.parse(stream, boundary, content_length)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 519, in parse
return self.cls(form), self.cls(files)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/datastructures.py", line 406, in __init__
for key, value in mapping or ():
File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 517, in <genexpr>
form = (p[1] for p in formstream if p[0] == 'form')
File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 476, in parse_parts
for ellt, ell in self.parse_lines(file, boundary, content_length):
File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 395, in parse_lines
self.fail('Expected boundary at start of multipart data')
File "/usr/local/lib/python2.7/dist-packages/werkzeug/formparser.py", line 327, in fail
raise ValueError(message)
ValueError: Expected boundary at start of multipart data

最终我希望能够保存文件(可以是二进制文件),并获取表单数据&#39; Field1&#39;和&#39; Field2&#39;从字典。有任何想法吗?我也愿意使用其他方法。

0 个答案:

没有答案