I am working on a Flask app constructed as follows:
- The starting HTML template, controlled by a view, displays a text box, where the user can enter a SQL request to request a SQLite database connected to the app.
- In a second view, the request is executed, then the result is converted into a pandas dataframe, then converted in HTML, then included into a second template where it is displayed on the screen.
- This second template has a form to select two columns to choose to build a plotly figure, displayed on a third template, controlled by a third view.
I do not understand how to use the pandas dataframe created in the second view within the third view, since the view uses render_template and not return. I succeeded once by storing the dataframe into the Flask session variable, but this is suitable for real small dataframes only. I tried to read the HTML version of the dataframe directly from the template, but I do not understand how to do either.
Here is the code for views.py:
@app.route("/", methods=["GET", "POST"])
def index():
return render_template('base.html')
@app.route('/submit', methods=['POST'])
def submit():
request_recap = request.form.get('sqlr') # example : SELECT * FROM Soils
with engine.connect() as conn:
request_result = conn.execute(text(request_recap))
columns = request_result.keys()
request_result = request_result.fetchall()
df = pd.DataFrame(request_result, columns=columns)
# Here is the attempt with 'session'
session['df'] = df.to_json()
return render_template("result.html",
request_recap=request_recap,
request_result=df.to_html(index=False),
cols=df.columns)
@app.route('/plot', methods=["GET", "POST"])
def plot():
# Here is the attempt with 'session', how to do better ?
df = pd.read_json(session.get('df'))
x = request.form.get('var1')
y = request.form.get('var2')
fig = makefig(table=df, x=x, y=y)
return render_template("plot.html",
fig=fig.to_html())