Uploading file in python flask

别说谁变了你拦得住时间么 提交于 2021-01-28 01:15:51

问题


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>
    '''

回答1:


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




回答2:


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

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

  • disclaimer - I'm the author.


来源:https://stackoverflow.com/questions/31010819/uploading-file-in-python-flask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!