我上传后检索文件

时间:2016-04-02 20:50:16

标签: python flask upload

我正在创建一个简单的烧瓶应用,用户可以在其中上传文件。我在一个不同的模块中对csv做了很多计算,但最初,我试图读取几个列名称放在表单上的下拉输入中。我的问题更通用。用户上传文件后,如何实际传递该文件名以进行检索?在这个例子中,我需要将filename变量传递给SimpleForm()类。我很新,而且我无法通过

传递文件名
form = SimpleForm(filename)

以下是我尝试这样做的代码块。

    @app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
            if columns_len(filename):
                title = filename.split('.')[0].title() #creates the title
                form = SimpleForm(filename) # creates the form
                return render_template('analysis.html',title=title, form=form)
            else:
                flash(u'Your CSV has less than three columns.  Please re-upload', 'error')
        else:
            flash(u'Invalid file type.  Please re-upload', 'error')
    return render_template('index.html')

这是SimpleForm类:

class MultiCheckboxField(SelectMultipleField):
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()

# creates the simple form
class SimpleForm(Form):
    list_of_files = ['Standard New/Renew/Upsell/Downsell/Churn Analysis', 'Top Ten Customer Accounts','Churn Analysis']
    second_list = ['Analysis by category']
    files = [(x, x) for x in list_of_files]
    # create a list of value/description tuples

    test = pd.read_csv(filename, index_col = None, nrows = 0, header=0)
    second_files = [(x, x) for x in list(test.columns)]
    second_files = [(x, x) for x in second_list]
    acheckbox = MultiCheckboxField('Label', choices=files)
    bcheckbox = MultiCheckboxField('Label', choices=second_files)
    categories = SelectField('Label',choices = files)

此外,一般来说,在其他函数或模块中检索“filename”变量的最佳方法是什么?

0 个答案:

没有答案