在python烧瓶中上传文件

时间:2015-06-23 18:35:39

标签: python flask

我正在尝试将基本文本/ csv文件上传到我的网络应用程序上,该应用程序运行烧瓶以处理http请求。我试图在localhost here上运行的flask文档中关注婴儿示例。但是当我在我的页面上尝试这个代码时,它似乎上传但是然后只是挂起,实际上我的烧瓶服务器冻结了,我必须关闭终端再试一次...... Ctrl + C甚至无法工作。

我执行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)

apprun.py所在目录中的目录__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

这是我的views.py文件,其中包含我的所有路线:

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

2 个答案:

答案 0 :(得分:2)

问题在于您将错误的内容传递给allowed_filename()。您应该通过submitted_file.filename而不是submitted_file本身

答案 1 :(得分:0)

有一个库*可以通过Flask处理文件上传:

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

  • 免责声明-我是作者。