开发者

How to reset the file.stream in flask / werkzeug?

开发者 https://www.devze.com 2023-04-03 17:31 出处:网络
It seems to me, that you cannot access file.stream.read() after the file has been written with file.save(\'path\',filename\') and vice versa.

It seems to me, that you cannot access file.stream.read() after the file has been written with file.save('path',filename') and vice versa.

Example code (derived from the file uploading pattern):

import os
from flask import Flask, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename

UPLOAD_FOLDER = 'uploads/'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            print '##########################'
            print os.path.join(app.config['UPLOAD_FOLDER'],filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print file.stream.read() # <- gives no output
            print '##########################'
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/for开发者_如何学编程m-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

if __name__ == '__main__':
    app.run(debug=True)                    


You should be able to seek back to the start of the stream. (See Werkzeug's docs on werkzeug.datastructures.FileStorage). When you try to read the file a second time you start reading from the end of the file.

file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
file.stream.seek(0) # Go back to the start of the file
print file.stream.read() # <- should work now.
0

精彩评论

暂无评论...
验证码 换一张
取 消