lundi 16 avril 2018

How do I use Flask to show a generated matplotlib image on the same screen as the form?

Basically I am using matplotlib to generate charts that I want to then display directly to the user. The user fills out a form and the variables are passed to a few methods that create the chart. The code I currently have will show only the image and get rid of the form. Is it possible to display the image on the page so that the user can modify the queries/connections and see the results with each subsequent form submission?

Here is my code:

from flask import Flask, request, render_template, send_file, redirect, 
url_for
import MultipleDatabasesLib as mdl
import subprocess
import pandas as pd
import matplotlib as plt
from matplotlib import pyplot as plt

app = Flask(__name__)

xlabel = ""
ylabel = ""
graph_title = ""

@app.route('/')
def my_form():
    return render_template('my-form.html')


@app.route('/', methods=['POST'])
def my_form_post():

    df = pd.DataFrame()
    df_group = pd.DataFrame()
    fig_size = plt.rcParams["figure.figsize"]
    fig_size[0] = 15
    fig_size[1] = 12
    plt.rcParams["figure.figsize"] = fig_size
    base = "C:/Python36-32/GraphFactory/Final_csv.csv"

    conn1 = request.form['conn1']
    conn2 = request.form['conn2']
    sql1 = request.form['sql1']
    sql2 = request.form['sql2']
    charttype = request.form['charttype']
    xlabel = request.form['xLabel']
    ylabel = request.form['yLabel']
    groupBy = request.form['groupBy']

    graph_title = charttype + "Chart"
    mdl.gen_csv(conn1, conn2, sql1, sql2)
    df = pd.read_csv(base)
    df_group = df.groupby(['YR', 'INSTANCE']).size()

    print(charttype)

    if charttype == "bar":
        mdl.bar_plot(xlabel, ylabel, graph_title, df_group)

    elif charttype == "pie":
        mdl.pie_plot(xlabel, ylabel, graph_title, df_group)

    elif charttype == "line":
        mdl.line_plot(xlabel, ylabel, graph_title, df_group)

    elif charttype == "hist":
        mdl.hist_plot(xlabel, ylabel, graph_title, df_group)

    return send_file("plt.png", mimetype='image/gif')


app.run(host='0.0.0.0', port=33)




Aucun commentaire:

Enregistrer un commentaire