Hello World,
Новое в Python и FLASK, я хочу загрузить, обработать и загрузить CSV-файл из flask.
Следующий код дает мне запрошенный вывод, хранится в "app.py":
from flask import Flask, make_response, request
import io
import csv
import pandas as pd
app = Flask(__name__)
@app.route('/')
def form():
return """
<html>
<body>
<h1>Data Processing</h1>
</br>
</br>
<p> Insert your CSV file and then download the Result
<form action="/transform" method="post" enctype="multipart/form-data">
<input type="file" name="data_file" class="btn btn-block"/>
</br>
</br>
<button type="submit" class="btn btn-primary btn-block btn-large">Pocess</button>
</form>
</body>
</html>
"""
@app.route('/transform', methods=["POST"])
def transform_view():
# Load DF
df = pd.read_csv(request.files.get('data_file'))
# Process
df['New'] = df['col1'].apply(lambda x: '{0:0>10}'.format(x))
# Send Response
resp = make_response(df.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename= export.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
if __name__ == "__main__":
app.run(debug=True)
Вопрос После разбиения моего файла на индекс. html и app.py, Как можно Я их подключаю? Я пробовал render_template, но безуспешно
РЕДАКТИРОВАТЬ
После проверки ваших комментариев ниже, что я сделал:
Папка:
- Пользователь / pro / app.py
- Пользователь / pro / templates / index. html
- Пользователь / pro / templates / images / lo go .jpg
- Пользователь / pro / templates / my css. css
Разделить предыдущий файл на app.py и index. html
App.py выглядит следующим образом
from flask import Flask, make_response, request, render_template
import io
import csv
import pandas as pd
from datetime import datetime
app = Flask(__name__, template_folder='C:/Users/pro/templates')
@app.route('/')
def home():
return render_template('index.html')
@app.route('/transform', methods=["POST"])
def transform_view():
# Load DF
df = pd.read_csv(request.files.get('data_file'))
# Process
df['New'] = df['col1'].apply(lambda x: '{0:0>10}'.format(x))
# Send Response
resp = make_response(df.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename= export.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
if __name__ == "__main__":
app.run(debug=True)
Index. html выглядит следующим образом
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>ML API</title>
<link href="mycss.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="login"> <br/><br/><br/>
<center>
<img src= "images/logo.jpg" width="550" height="145"> <br/><br/>
<input type="file" class="btn btn-primary btn-block btn-large" name="myfile" required="required"/> <br/>
<button type="submit" class="btn btn-primary btn-block btn-large" >Process</button>
</center>
</div>
</body>
</html>
Проблема заключается в том, что теперь никакой процесс не выполняется. Когда я нажимаю, чтобы обработать, ничего не происходит. Ранее я был в состоянии загрузить файл CSV с новым столбцом. Кроме того, изображение не отображается.

Спасибо за помощь