我希望有一个包含两个上载的网页(input
type = submit),该页面接受两个csv并添加其内容。例如:
# csv1
col1,col2
1,2
3,4
# csv2
col1,col2
10,20
30,40
预期输出:
col1,col2
11,22
33,44
但是我暂时不关心输出;只是实现两个<input type="submit">
字段并将其内容存储在某处的输入功能。我想这样做而不必保存(例如,使用file.save
),因为这可能会导致多个用户在服务器目录中保存多个文件时出错(我认为?)。我也不能真正使用models.py
ORM,因为不同的用户可能使用不同的输入列名称(例如c1
,c2
等),并且列数是可变的。但是,我们可以假设两个输入将始终具有相同的尺寸。
我能够写一条路由来处理one <input>
元素,但是我不确定该怎么做two。我到目前为止所拥有的是:
app.py([源])(https://www.semicolonworld.com/question/59622/not-able-to-parse-a-csv-file-uploaded-using-flask)
from flask import Flask, make_response, request, render_template
import io
import csv
app = Flask(__name__)
@app.route('/')
def form():
return render_template("index.html")
@app.route('/transform', methods=["POST"])
def transform_view():
f = request.files['data_file']
if not f:
return "No file found"
stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
csv_contents = [] # this will be a list of lists
for row in csv_input:
print(row)
csv_contents.append(row)
# automatic download of output commented out
#stream.seek(0)
#result = transform(stream.read().replace("=", ","))
#response = make_response(result)
#response.headers["Content-Disposition"] = "attachment; filename=result.csv"
return redirect("/")
if __name__ == "__main__":
app.run(debug=True)
index.html
<html>
<head>
<title></title>
</head>
<body>
<h1>Upload CSV</h1>
<form action="/transform" method="post" enctype="multipart/form-data">
<input type="file" name="data_file" />
<input type="submit" />
</form>
</body>
</html>
我试图弄清楚如何编写两条路线,每个input
字段一条?
结果我只能修改index.html
并使用单个submit
字段(按钮)来提交POST请求。
在app.py中,将transform_view()
更改为:
@app.route('/transform', methods=["POST"])
def transform_view():
f = request.files['input_file1']
if not f:
return "Input file 1 not found!"
f = request.files['input_file2']
if not f:
return "Input file 2 not found!"
stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
csv_contents = [] # this will be a list of lists
for row in csv_input:
csv_contents.append(row)
stream = io.StringIO(g.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
csv_contents2 = [] # this will be a list of lists
for row in csv_input:
csv_contents2.append(row)
return redirect("/")
和index.html更改为:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<h1>Input files (csv)</h1>
<form action="/transform" method="post" enctype="multipart/form-data">
<input type="file" name="input_file1" id="input_file1">
<input type="file" name="input_file2" id="input_file2">
<br>
<input type="submit" value="Upload Files" name="submit">
</form>
</div>
</body>
</html>