在 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()
两种情况都可以调用吗?