15

我正在尝试在 Flask 中测试我的 upload() 方法。唯一的问题是 Flask 中的FileStorage对象有一个方法 save() ,而 python File对象没有。

我像这样创建我的文件:

file = open('documents-test/test.pdf')

但我无法测试我的upload() 方法,因为该方法使用save()。

任何想法如何将此 File 对象转换为 Flask Filestorage 对象?

4

3 回答 3

24

http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage

我需要将烧瓶FileStorage对象用于测试框架和应用程序本身之外的实用程序,基本上复制了使用表单上传文件的工作方式。这对我有用。

from werkzeug.datastructures import FileStorage
file = None
with open('document-test/test.pdf', 'rb') as fp:
    file = FileStorage(fp)
file.save('document-test/test_new.pdf')
于 2014-12-16T17:40:15.980 回答
3

Flask 测试客户端的getandpost方法在后台调用werkzeug.test.EnvironBuilder- 因此,如果您将字典作为关键字参数data与您的文件一起传递,那么您应该能够使用它:

def test_upload():
    with open("document-test/test.pdf", "rb") as your_file:
        self.app.post("/upload", data={"expected_file_key": your_file})
        # Your test here
于 2013-08-16T04:21:23.943 回答
0

@neurosnap 的回答让我开始了,但效果不佳。以下做了...

file_loc = open('./tests/sample data/2 Candidates.csv', 'rb')
file = werkzeug.datastructures.FileStorage(file_loc)
file.save(dst='document-test/test_new.pdf')
file_loc.close()

如果最后没有关闭文件,Python 会抛出错误。

于 2020-11-18T20:19:23.637 回答