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

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

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

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

但令人困惑的是,在某些情况下 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')

打印

<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()吗?

最佳答案

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

关于Python - flask.request.files.stream 应该是什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18246309/

相关文章:

python - jinja2 设置背景图像

python - 计算 Google AppEngine 中的子查询数

python - 在 zipfile 中从 URL 读取 shapefile 时,错误为初始值不是 str

javascript - 通过 Javascript/Ajax 上传多个文件?

java - 上传文件时出现 IndexOutOfBoundsException - Java

python-3.x - 使用 flask 时找不到404错误

python - Fasttext .vec 和 .bin 文件之间的区别

python - 连接 mysql wamp 和 django 时出现问题?

java - 如何使用 Java Servlet 和 JSP 以及其他字段从同一页面上传两个文件?

javascript - 如何修复Python Flask中的 "Undefined is not JSON serializable"