Hello World,
New in Python and FLASK, I want to upload, process and download a csv file from flask.
The following code gives me the requested output, stores in "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)
Question After splitting my file into index.html and app.py, How can I connect them? I have tried render_template but without success
EDIT
After checking your comments, below is what I've done:
Folder:
- User/pro/app.py
- User/pro/templates/index.html
- User/pro/templates/images/logo.jpg
- User/pro/templates/mycss.css
Split The previous file into app.py and index.html
App.py looks like this
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 looks like this
<!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>
The problem is that now no process is being done. When I click to process, nothing happen. Before, I was able to download the CSV file with the new column. Furthermore, the image is not displaying.
Thanks for anyone helping