Python - flask.request.files.stream应该是什么类型的?

neu*_*ont 3 python file-upload python-2.x flask

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

f = flask.request.files[input_name]
stream = f.stream
# then use the stream
Run Code Online (Sandbox Code Playgroud)

但令人困惑的是,在某些情况下stream是一个BytesIO实例,但也有机会成为一个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')
Run Code Online (Sandbox Code Playgroud)

它打印

<type '_io.BytesIO'>
<type 'file'>
Run Code Online (Sandbox Code Playgroud)

PNG文件来自github:

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

我想知道为什么Flask会以这种方式行事.如果我希望上传的数据进入数据库,f.stream.read()两种情况下都可以调用吗?

Ble*_*der 7

小于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.
    """

    ...
Run Code Online (Sandbox Code Playgroud)

资源