I need to insert Python code so that it reads two variables from the data entry windows in HTML, as well as two excel files, runs the code when the button is clicked, and outputs the result of the program to a special .
How can this be done?
I tried using two frameworks Flask and Py Script. It is not possible to make the Python code take data and excel tables from the input windows and output the result to an html page.
df and df1 should read from the HTML page from the windows id="file-input-1" and id="file-input-2", respectively. your_choice from id="pipeline-input", and your_choice_year from id="data-input". when you click on the id="runCodeButton" button, the python code should be triggered and output the result result to the page
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/calculate', methods=['POST'])
def calculate():
df = pd.read_excel(request.files['file-input-1'], index_col=0)
df1 = pd.read_excel(request.files['file-input-2'], index_col=0)
your_choice = request.form['pipeline-input']
your_choice_year = int(request.form['data-input'])
name_list = df.index.tolist()
def f(your_choice, df, df1, name_list, your_choice_year):
...........
return render_template('index.html', result=result)
if __name__ == '__main__':
app.run(debug=True)
2
Answers
You definitely don’t need PyScript for this task. Here is an example how to upload two excel files from html page to the python code using Flask and process it using Pandas.
app.py:
As @detlef correctly mentioned you should use
name
attribute of the<input>
instead ofid
.index.html:
Note, this is not good solution but only the example how to deal with files in flask. Use flashing rather to pass error to the template. Read how to correctly save files in flask especially part about secure_filename. I have repeated myself twice for file reading logic but this code should be generalized to some function. This code simply calls
pd.read_excel
but it would be better to handle any possible errors here and notify user about it.It is indeed possible to use PyScript to handle Excel files in the browser, if you choose to go that route. Here’s an example with two upload
<input>
s and a button that prints the size of both:Note that this is a very minimal example – there’s no error handling around what happens if one/both of the files don’t exist, are unparsable, etc.
Note too that this is for the current release of PyScript (
2023.05.1
at time of writing). An upcoming release changes a bit about how thepy-[event]
syntax works, but not much else.