如何在Flask或Pandas中动态填充下拉菜单以显示来自CSV的列名?

huangapple go评论71阅读模式
英文:

How to dynamically populate dropdown menus with column names from csv in Flask or Pandas?

问题

我正在构建一个Flask应用程序允许用户上传CSV文件并使用下拉菜单选择文件中的三列我希望动态填充下拉菜单使用上传文件的列名最终目标是将列名分配给变量col1col2col3以便我可以在Python脚本中引用它们

我正在尝试让用户映射列以便我知道要用Python对数据进行怎样的操作对Flask还很生疏但感觉我已经很接近了

**我尝试过的方法:**

我尝试修改上传功能从上传的文件中读取列名并将它们传递到upload.html模板但是我仍然遇到下拉菜单未填充列名的问题

以下是我的代码

**app.py**

from flask import Flask, render_template, request
import pandas as pd

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        file = request.files.get('file')
        if file and file.filename.endswith('.csv'):
            df = pd.read_csv(file)
            col_names = df.columns.tolist()
            return render_template('upload.html', col_names=col_names)
        else:
            return "Invalid file format"
    else:
        return render_template('upload.html')

if __name__ == '__main__':
    app.run(debug=True)

**upload.html**

<form action="/upload" method="POST" enctype="multipart/form-data">
    <label for="file">File:</label>
    <input type="file" id="file" name="file"><br />
    <label for="col1">Column 1:</label>
    <select id="col1" name="col1">
        {% for col in col_names %}
        <option value="{{ col }}">{{ col }}</option>
        {% endfor %}
    </select><br />
    <label for="col2">Column 2:</label>
    <select id="col2" name="col2">
        {% for col in col_names %}
        <option value="{{ col }}">{{ col }}</option>
        {% endfor %}
    </select><br />
    <label for="col3">Column 3:</label>
    <select id="col3" name="col3">
        {% for col in col_names %}
        <option value="{{ col }}">{{ col }}</option>
        {% endfor %}
    </select><br />
    <button>Upload</button>
</form>
英文:

I'm building a Flask app that allows users to upload a CSV file and select three columns from the file using dropdown menus. I want to dynamically populate the dropdown menus with the column names from the uploaded file. The end goal is to assign the column names to variables col1, col2, col3 so that I can reference them in a python script.

I'm trying to get the user to map columns so I know what the data is to manipulate it with Python. New to Flask, but feel like I'm close!

What I've tried:

I've tried modifying the upload function to read the column names from the uploaded file and pass them to the upload.html template. I'm still having issues with the dropdown menus not being populated with the column names.

Here's my code:

app.py

from flask import Flask, render_template, request
import pandas as pd
app = Flask(__name__)
@app.route(&#39;/&#39;)
def home():
return render_template(&#39;home.html&#39;)
@app.route(&#39;/upload&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])
def upload():
if request.method == &#39;POST&#39;:
file = request.files.get(&#39;file&#39;)
if file and file.filename.endswith(&#39;.csv&#39;):
df = pd.read_csv(file)
col_names = df.columns.tolist()
return render_template(&#39;upload.html&#39;, col_names=col_names)
else:
return &quot;Invalid file format&quot;
else:
return render_template(&#39;upload.html&#39;)
if __name__ == &#39;__main__&#39;:
app.run(debug=True)

upload.html

&lt;form action=&quot;/upload&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt;
&lt;label for=&quot;file&quot;&gt;File:&lt;/label&gt;
&lt;input type=&quot;file&quot; id=&quot;file&quot; name=&quot;file&quot;&gt;&lt;br /&gt;
&lt;label for=&quot;col1&quot;&gt;Column 1:&lt;/label&gt;
&lt;select id=&quot;col1&quot; name=&quot;col1&quot;&gt;
{% for col in col_names %}
&lt;option value=&quot;{{ col }}&quot;&gt;{{ col }}&lt;/option&gt;
{% endfor %}
&lt;/select&gt;&lt;br /&gt;
&lt;label for=&quot;col2&quot;&gt;Column 2:&lt;/label&gt;
&lt;select id=&quot;col2&quot; name=&quot;col2&quot;&gt;
{% for col in col_names %}
&lt;option value=&quot;{{ col }}&quot;&gt;{{ col }}&lt;/option&gt;
{% endfor %}
&lt;/select&gt;&lt;br /&gt;
&lt;label for=&quot;col3&quot;&gt;Column 3:&lt;/label&gt;
&lt;select id=&quot;col3&quot; name=&quot;col3&quot;&gt;
{% for col in col_names %}
&lt;option value=&quot;{{ col }}&quot;&gt;{{ col }}&lt;/option&gt;
{% endfor %}
&lt;/select&gt;&lt;br /&gt;
&lt;button&gt;Upload&lt;/button&gt;
&lt;/form&gt;

答案1

得分: 1

在upload.html中:

<form action="/upload?col_names={{ col_names }}" method="POST" enctype="multipart/form-data">

在app.py中:

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    col_names = request.args.get('col_names')
    if request.method == 'POST':
        file = request.files.get('file')
        if file and file.filename.endswith('.csv'):
            df = pd.read_csv(file)
            col1 = request.form.get('col1')
            col2 = request.form.get('col2')
            col3 = request.form.get('col3')
            return render_template('upload.html', col_names=col_names, col1=col1, col2=col2, col3=col3)
        else:
            return "Invalid file format"
    else:
        return render_template('upload.html', col_names=col_names)

这样,您可以在upload()函数中访问col1col2col3的值,并将它们用于使用Python操作CSV文件中的数据。

英文:

Add the column names to the form action in the upload.html template and then retrieve the values with the request.form.get() method in the upload() function in app.py.

In upload.html:

&lt;form action=&quot;/upload?col_names={{ col_names }}&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt;

In app.py:

@app.route(&#39;/upload&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])
def upload():
col_names = request.args.get(&#39;col_names&#39;)
if request.method == &#39;POST&#39;:
file = request.files.get(&#39;file&#39;)
if file and file.filename.endswith(&#39;.csv&#39;):
df = pd.read_csv(file)
col1 = request.form.get(&#39;col1&#39;)
col2 = request.form.get(&#39;col2&#39;)
col3 = request.form.get(&#39;col3&#39;)
return render_template(&#39;upload.html&#39;, col_names=col_names, col1=col1, col2=col2, col3=col3)
else:
return &quot;Invalid file format&quot;
else:
return render_template(&#39;upload.html&#39;, col_names=col_names)

With that you can access the values of col1, col2, and col3 in the upload() function and use them to manipulate the data in the CSV file with Python.

huangapple
  • 本文由 发表于 2023年2月19日 03:19:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495801.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定