简体   繁体   中英

Uploading file in python flask

I am trying to incorporate uploading a basic text/csv file on my web app which runs flask to handle http requests. I tried to follow the baby example in flasks documentation running on localhost here . But when I try this code on my page it seems to upload but then just hangs and in fact my flask server freezes and I have to close terminal to try again...Ctrl+C doesn't even work.

I execute run.py :

#!/usr/bin/env python
from app import app

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False, use_reloader=False)

and app is a directory in the same directory where run.py is with the following __init__.py :

import os
from flask import Flask
from werkzeug import secure_filename

#Flask object initialization
#app flask object has to be created before importing views below
#because it calls "import app from app"
UPLOAD_FOLDER = '/csv/upload'
ALLOWED_EXTENSIONS = set(['txt', 'csv'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

and here is my views.py file which has all my routes:

from flask import render_template, request, redirect, url_for
from app import app
import os

#File extension checking
def allowed_filename(filename):
    return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
@app.route('/index.html', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        submitted_file = request.files['file']
        if submitted_file and allowed_filename(submitted_file):
            filename = secure_filename(submitted_file.filename)
            submitted_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            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/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

The problem is that you're passing the wrong thing to allowed_filename() . You should be passing submitted_file.filename not submitted_file itself

There's a library* to handle file uploads with Flask:

https://github.com/joegasewicz/flask-file-upload

  • disclaimer - I'm the author.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM