检索文件一旦我上传我

2024-06-30 15:02:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个简单的flask应用程序,用户在其中上传一个文件。我在另一个模块中对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”变量的最佳方式是什么


Tags: columnsoftheformindexiftitlefiles