Python文件对象到Flask的FileStorage

arn*_*rts 8 python testing flask

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

我像这样创建我的文件:

file = open('documents-test/test.pdf')
Run Code Online (Sandbox Code Playgroud)

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

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

neu*_*nap 12

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

我需要将flask 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')
Run Code Online (Sandbox Code Playgroud)


Sea*_*ira 4

Flask 测试客户端的 和 方法在后台调用-因此,如果您将字典作为关键字参数传递get给您的文件,您应该能够使用它:postwerkzeug.test.EnvironBuilderdata

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
Run Code Online (Sandbox Code Playgroud)