Python - flask.request.files.stream应该是什么类型? [英] Python - What type is flask.request.files.stream supposed to be?
问题描述
f = flask.request.files [input_name]
stream = f.stream
#然后使用流
但是有些情况下 stream 是一个
BytesIO
实例,是一个文件
对象。
我已经用这种方式测试过了
从瓶子导入瓶子,请求
导入cStringIO
app =瓶子('test')
@ app.route(/,methods = ['POST'])
def index():
if request.method =='POST':
f = request.files [文件']
打印类型(f.stream)
def send_file(客户端,名称):
打开(名称,'rb')作为f:
client.post('/',data = {'file':(cStringIO.StringIO(f.read()),name)})
if __name__ ==__main__:
用app.test_client()作为客户端:
send_file(客户端,'homercat.png')
send_file(客户端,'megacat-2.png')
它打印
< type'_io.BytesIO'>
PNG文件来自github:
http://octodex.github.com/images/homercat.png
http://octodex.github.com/images/megacat-2.png
我想知道为什么Flask以这种方式行事。如果我想要上传的数据到数据库,在这两种情况下调用 f.stream.read()
是否可以?
小于1024 * 500字节的文件被写入到一个StringIO对象,而大于该阈值的文件被写入到临时文件中。 $ b $
它是Werkzeug测试框架的一部分,但是这个函数不是在线文档的一部分:
def stream_encode_multipart(values,use_tempfile = True,threshold = 1024 * 500,
boundary = None,charset ='utf-8'):
编码字典或字符串描述符或
:class:`FileStorage`对象)转换成一个多重编码的字符串,存储在文件描述符中的
...
In Flask (Flask-0.10.1 installed via pip) I've tried to handle uploaded files like this
f = flask.request.files[input_name]
stream = f.stream
# then use the stream
But it's confusing that in some cases stream
is a BytesIO
instance, but also a chance to be a file
object.
I've tested in this way
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')
It prints
<type '_io.BytesIO'>
<type 'file'>
The PNG files are from github:
http://octodex.github.com/images/homercat.png http://octodex.github.com/images/megacat-2.png
I wonder why Flask behaves in such way. And if I want the uploaded data to go to the database, is it ok to call f.stream.read()
in both cases?
Files smaller than 1024 * 500 bytes are written to a StringIO object, while files greater than that threshold are written to temporary files.
It's part of Werkzeug's testing framework, but that function isn't part of the online documentation:
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.
"""
...
这篇关于Python - flask.request.files.stream应该是什么类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!