【问题标题】:Python - What type is flask.request.files.stream supposed to be?Python - flask.request.files.stream 应该是什么类型?
【发布时间】:2013-08-15 04:25:07
【问题描述】:

在 Flask(通过 pip 安装的 Flask-0.10.1)中,我尝试过像这样处理上传的文件

f = flask.request.files[input_name]
stream = f.stream
# then use the stream

但令人困惑的是,在某些情况下 streamBytesIO 实例,但也有机会成为 file 对象。

我用这种方式测试过

from flask import Flask, request
import cStringIO

app = Flask('test')

@app.route("/", methods=['POST'])
def index():
    if request.method == 'POST':
        f = request.files['file']
        print type(f.stream)

def send_file(client, name):
    with open(name, 'rb') as f:
        client.post('/', data={'file': (cStringIO.StringIO(f.read()), name)})

if __name__ == "__main__":
    with app.test_client() as client:
        send_file(client, 'homercat.png')
        send_file(client, 'megacat-2.png')

打印出来

<type '_io.BytesIO'>
<type 'file'>

PNG 文件来自 github:

http://octodex.github.com/images/homercat.png http://octodex.github.com/images/megacat-2.png

我想知道为什么 Flask 会这样。如果我想让上传的数据进入数据库,这两种情况都可以调用f.stream.read()吗?

【问题讨论】:

    标签: python file-upload flask python-2.x


    【解决方案1】:

    小于 1024 * 500 字节的文件被写入 StringIO 对象,而大于该阈值的文件被写入临时文件。

    它是 Werkzeug 测试框架的一部分,但该功能不是在线文档的一部分:

    def stream_encode_multipart(values, use_tempfile=True, threshold=1024 * 500,
                                boundary=None, charset='utf-8'):
        """Encode a dict of values (either strings or file descriptors or
        :class:`FileStorage` objects.) into a multipart encoded string stored
        in a file descriptor.
        """
    
        ...
    

    Source

    【讨论】:

    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多