Python File 对象到 Flask 的 FileStorage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18249949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python File object to Flask's FileStorage
提问by arnoutaertgeerts
I'm trying to test my upload() method in Flask. The only problem is that the FileStorageobject in Flask has a method save() which the python Fileobject does not have.
我正在尝试在 Flask 中测试我的 upload() 方法。唯一的问题是Flask中的FileStorage对象具有 python File对象没有的save() 方法。
I create my file like this:
我像这样创建我的文件:
file = open('documents-test/test.pdf')
But I cannot test my upload() method because that method uses save().
但是我无法测试我的 upload() 方法,因为该方法使用了 save()。
Any ideas how to convert this File object to a Flask Filestorage object?
任何想法如何将此 File 对象转换为 Flask Filestorage 对象?
回答by Sean Vieira
The get
and post
methods of the Flask test client invoke werkzeug.test.EnvironBuilder
under the hood - so if you pass in a dictionary as the keyword argument data
with your file you should be able to work with it then:
Flask 测试客户端的get
andpost
方法在后台调用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
回答by neurosnap
http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage
http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage
I needed to use the flask FileStorage
object for a utility outside of the testing framework and the application itself, essentially replicating how uploading a file works using a form. This worked for me.
我需要将烧瓶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')