[Tutor] Flask File Uploads and Sessions

Doran, Harold C. HDoran at air.org
Fri May 8 12:22:55 EDT 2020


I am new to Flask (and relatively new to python) and am working to do the following: 1) read in a .csv data file 2) populate a drop down menu with the variables (column names) in the data file read in 3) User chooses a variable from the drop down menu and the mean of that column is computed.

I am successful with both (1) and (2) but have now spent more than 4 days trying to solve (3) and cannot find a tutorial or documentation. I'm certain it exists, and think my "newness" to the concepts needed might be masking an obvious answer. Below is the relevant portion of my app.py file which runs my flask app and some minimal HTML.

When running this, I can read in a file and my drop down is populated as expected. For now, the mean of some variable is hard coded (that's easy to solve). After reading and experimenting for days, I believe the problem is that my file orig_df is not stored in a session. In fact, if I uncomment the line that hard codes a local read in I can do everything I want.

So, what I want is for the data orig_df to be read in from the UI and reusable for things I would want to do with it (compute statistics on columns I choose, etc).

I am terribly lost. This link below is to where I have fully built and deployed a similar system using R/shiny and my goal is to port my code from R to python and rebuild my app using flask. Can anyone offer some support on how I can make my file orig_df available so that it can be used in a session? I do not want this to be a global variable or even stored on the server, the file should be available to the user only during their browser session and then it would vaporize when they close their browser session.

Thank you

https://shiny.airast.org/METRICS/

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

app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def data_tools_upload():
    if request.method == 'POST':
        orig_df = pd.read_csv(request.files.get('file'))
        #orig_df = pd.read_csv(/path/to/file.csv)
        var2use = request.form.get("vars2use")
        vars = list(orig_df.columns)
        mean = orig_df[vars[4]].mean()
        dims = orig_df.shape
        message = 'You have data! There are %s rows and %s columns and the variable %s has mean %s' % (dims[0],dims[1],vars[4],round(mean,3))
        table = orig_df.head(10).to_html(classes='data', header = "true")
        return render_template('upload2.html', tables = [table], message = message, vars = vars, showVar=var2use)
    return render_template('upload2.html')

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

And some minimal HTML


<!DOCTYPE html>

<html>

    <body>



<h3> Read in a data file </h3>



<br>



<form method=post enctype=multipart/form-data>

    <input type=file name=file class = "btn btn-outline-secondary">

    <input type=submit value=Upload class = "btn btn-outline-secondary">

</form>



<br>



<form action = "{{url_for('data_tools_upload')}}" method = "POST">

    <select name= vars method="POST" action="\">

        {% for var in vars %}

        <option value= "{{ var }}" SELECTED>{{ var }}</option>"

        {% endfor %}

    </select>

    </select>

</form>





<center>

    <h1>

    {{message}}

    {{showVar}}

    </h1>

    <br>

        <small>

        {% for table in tables %}

                    {{ table|safe }}

        {% endfor %}



        </small>

</center>



</body>

</html>



More information about the Tutor mailing list