1

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.

enter image description here

Thanks for anyone helping

A2N15
  • 595
  • 4
  • 20

2 Answers2

0

You should put index.html in a folder named templates:

see https://pythonise.com/series/learning-flask/rendering-html-files-with-flask for example for full explanation

Concerning launching flask from another computer see: Configure Flask dev server to be visible across the network

After your edit:

you've delete the form part: "

Also you're images should be in a folder named static, see https://pythonise.com/series/learning-flask for example. Ep 4 and 7 in particular

ThomaS
  • 815
  • 4
  • 13
  • Thanks @ThomaS for your help, the question has been edited with your suggestion. – A2N15 Mar 09 '20 at 07:13
  • I edited my answer to the editing of you're question – ThomaS Mar 09 '20 at 08:56
  • Thanks @ThomaS for your tip with Image, it works now. However, if I keep def form, what am I supposed to put inside? because I want have already the same content into index.html. Therefore, how can I link muy index.htlm to my app.py? – A2N15 Mar 09 '20 at 09:43
  • You should still use form to wrap your input and buttons in the index.html, the form action is the one calling /transform url from the index page – ThomaS Mar 09 '20 at 09:45
0

I think I can help, if you separate your html from your Python file. The HTML file should go in a "templates" folder because that's where flask reads all he HTML files. Also don't forget to import "render_template". Hope this helps! (Could you also give me a little more information about your bonus question?)

  • Thanks @Kirshan Murali, but even while importing render_template, it seems that I missed some step but which one :x – A2N15 Mar 09 '20 at 07:14