动态填充下拉列表;将 "filename" 传递给 SimpleForm() Class

dynamically populate dropdown; passing "filename" to SimpleForm() Class

我正在尝试根据用户上传的 csv 中的列名动态填充下拉列表。在用户上传文件(变量名是文件名)并被重定向到下一页/analysis/ 后,我如何将文件名实际传递给 SimpleForm(form) class 以实际生成下拉列表? 代码是问题是

form = SimpleForm(filename)

我知道我不能将文件名直接传递给 class SimpleForm(object) 但我该怎么做?

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


class SimpleForm(Form):
    list_of_files = ['Standard New/Renew/Upsell/Downsell/Churn Analysis', 'Top Ten Customer Accounts','Churn Analysis']
    # create a list of value/description tuples
    files = [(x, x) for x in list_of_files]
    test = pd.read_csv(filename, index_col = None, nrows = 0, header=0)
    second_list = 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)



@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
                    return redirect(url_for('analysis', filename=filename))
                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')

    @app.route('/analysis/<filename>', methods=['GET','POST'])
    def analysis(filename):

        form = SimpleForm(filename)
        return render_template('analysis.html', filename=filename, form=form)

您必须定义 __init__ 方法来接受您的参数并在那里设置 choices

class SimpleForm(Form):
    acheckbox = MultiCheckboxField('Label')
    bcheckbox = MultiCheckboxField('Label')
    categories = SelectField('Label')

    def __init__(self, filename, *args, **kwargs):
        super(SimpleForm, self).__init__(*args, **kwargs)

        list_of_files = ['Standard New/Renew/Upsell/Downsell/Churn Analysis', 'Top Ten Customer Accounts','Churn Analysis']
        # create a list of value/description tuples
        files = [(x, x) for x in list_of_files]
        test = pd.read_csv(filename, index_col = None, nrows = 0, header=0)
        second_list = list(test.columns)
        second_files = [(x, x) for x in second_list]

        self.acheckbox.choices = files
        self.bcheckbox.choices = second_files
        self.categories.choices = files