我在Python3.3中使用了Flask,我知道支持仍然是实验性的,但是在尝试测试文件上传时我遇到了错误。我使用的是unittest.TestCase,基于Python2.7的例子,我在我正在尝试的文档中看到
rv = self.app.post('/add', data=dict(
file=(io.StringIO("this is a test"), 'test.pdf'),
), follow_redirects=True)和得到
TypeError: 'str' does not support the buffer interface我在io.StringIO上尝试过几种变体,但是找不到任何有用的东西。任何帮助都是非常感谢的!
完整的堆栈跟踪是
Traceback (most recent call last):
File "archive_tests.py", line 44, in test_add_transcript
), follow_redirects=True)
File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 771, in post
return self.open(*args, **kw)
File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/flask/testing.py", line 108, in open
follow_redirects=follow_redirects)
File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 725, in open
environ = args[0].get_environ()
File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 535, in get_environ
stream_encode_multipart(values, charset=self.charset)
File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 98, in stream_encode_multipart
write_binary(chunk)
File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 59, in write_binary
stream.write(string)
TypeError: 'str' does not support the buffer interface发布于 2013-11-19 19:48:09
在Python3中,您需要使用io.BytesIO() (具有一个字节值)来模拟上传的文件:
rv = self.app.post('/add', data=dict(
file=(io.BytesIO(b"this is a test"), 'test.pdf'),
), follow_redirects=True)注意,定义一个b'...'文本的bytes字符串。
在Python2测试示例中,StringIO()对象保存一个字节字符串,而不是unicode值,在Python3中,io.BytesIO()是等效的。
https://stackoverflow.com/questions/20080123
复制相似问题