[英]Testing file upload with Flask and Python 3
我正在使用帶有Python 3.3的Flask,我知道支持仍然是實驗性的,但我在嘗試測試文件上傳時遇到了錯誤。 我正在使用unittest.TestCase
並基於我在我嘗試的文檔中看到的Python 2.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
在Python 3中,您需要使用io.BytesIO()
(帶有字節值)來模擬上傳的文件:
rv = self.app.post('/add', data=dict(
file=(io.BytesIO(b"this is a test"), 'test.pdf'),
), follow_redirects=True)
注意b'...'
字符串定義bytes
文字。
在Python 2測試示例中, StringIO()
對象包含字節字符串,而不是unicode
值,而在Python 3中, io.BytesIO()
是等效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.