简体   繁体   English

使用Flask和Python 3测试文件上载

[英]Testing file upload with Flask and Python 3

I'm using Flask with Python 3.3 and I know support is still experimental but I'm running into errors when trying to test file uploads. 我正在使用带有Python 3.3的Flask,我知道支持仍然是实验性的,但我在尝试测试文件上传时遇到了错误。 I'm using unittest.TestCase and based on Python 2.7 examples I've seen in the docs I'm trying 我正在使用unittest.TestCase并基于我在我尝试的文档中看到的Python 2.7示例

rv = self.app.post('/add', data=dict(
                               file=(io.StringIO("this is a test"), 'test.pdf'),
                           ), follow_redirects=True)

and getting 并得到

TypeError: 'str' does not support the buffer interface

I've tried a few variations around io.StringIO but can't find anything that works. 我在io.StringIO周围尝试了一些变化,但找不到任何有用的东西。 Any help is much appreciated! 任何帮助深表感谢!

The full stack trace is 完整的堆栈跟踪是

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

In Python 3, you need to use io.BytesIO() (with a bytes value) to simulate an uploaded file: 在Python 3中,您需要使用io.BytesIO() (带有字节值)来模拟上传的文件:

rv = self.app.post('/add', data=dict(
                               file=(io.BytesIO(b"this is a test"), 'test.pdf'),
                           ), follow_redirects=True)

Note the b'...' string defining a bytes literal. 注意b'...'字符串定义bytes文字。

In the Python 2 test examples, the StringIO() object holds a byte string, not a unicode value, and in Python 3, io.BytesIO() is the equivalent. 在Python 2测试示例中, StringIO()对象包含字节字符串,而不是unicode值,而在Python 3中, io.BytesIO()是等效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM