How to add date input to HTML alongside with another input (station for example in my case)?

Viewed 46

First of all, I am a beginner to Flask, Javascript and and HTML/CSS. I am setting a simple data visualisation application to show model temperature data in comparison to the observed data for a given date and location (both will be chosen by the user).

This is snap of the current progress :

enter image description here

My flask app incorporates a function getData that reads temperature data from an SQL database.

app = Flask(__name__)
app.config['dbconfig'] = {'host': '127.0.0.1',
                        'user': 'root',
                        'password': '',
                        'database': 'controle'}
#Function to fetch the data (2 models + observation) from an SQL database
def getData(station, date):
    with UseDatabase(app.config['dbconfig']) as cursor:
        select_query = "SELECT * FROM score_temperature_{} where date = date".format(station)
        cursor.execute(select_query)
        idx, date, hours, T_model1, T_model2, T_obs = cursor.fetchall()[0]

    return idx, date, hours, T_model1, T_model2, T_obs '''

With a bit of reading and searching, I successfully managed to add the location (selected from a list) part with a callback function allowing the update of the graph interactively. The function gm takes the station (location) as a parameter. The date is set to a default value for now, but I would like to make it a variable to be selected interactivelly by the user as well. Following are the routes and functions I defined for my app.

@app.route('/')
def notdash():
   return render_template('index.html')

@app.route('/callback', methods=['GET', 'POST'])
def cb():
    return gm(request.args.get('data')) 

@app.route('/interactive')
def interactive():
    return render_template("chartsajax.html", graphJSON = gm())


#The following function creates the plot
def gm(CPM='izg', date = datetime.date.today()):
    idx, date, hours, T_model1, T_model2, T_obs = getData(CPM, date)
    colors = ['rgb(180,0,0)', 'rgb(0,0,189)', 'rgb(67,67,67)']
    fig = go.Figure()

    #model1 = BACHIR
    fig.add_trace(go.Scatter(x=hours, y=T_bachir, mode='lines', name='T_bachir', 
  line=dict(color=colors[0], width=2), connectgaps=True, ))

    #model2 = AROME
    fig.add_trace(go.Scatter(x=hours, y=T_arome, mode='lines', name='T_arome', 
  line=dict(color=colors[1], width=2), connectgaps=True, ))

    #Observed Temperature
    fig.add_trace(go.Scatter(x=hours, y=T_obs, mode='lines', name='T_obs', 
  line=dict(color=colors[2], width=2), connectgaps=True, ))

   fig.show()
   graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)    
   return graphJSON

Following is the HTML document. Plotly is used to render the graph, while a JQuery function is used to implement the callback to the server. Also, a Javascript function cb is defined The graph updates itself thanks to the "onchange" attribute in the input field. My wish is to do the same for the date input (Disclaimer : most of the code snippets are re-used from my search results).

 <!doctype html>
 <html>
 <head>
     <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        function cb(selection) {
            $.getJSON({
                url: "/callback", data: { 'data': selection }, success: function (result) {
                    Plotly.newPlot('chart', result, {staticPlot: true});;
                }
            });
        }
    </script>
</head>

<body style="font-family:arial, sans-serif">
    <div class="container">
        <h1>Controle des températures </h1>
        <h2></h2>
        <label for="list_CPM">
            Choisissez le CPM
        </label>
        <h3><datalist> Tag</h3>
        <div class="text-container">

            <select id="fname" onchange="cb(this.value)">
                <option value="izg">Inzegane</option>
                <option value="mass">Al-Massira</option>
                <option value="glm">Guelmime</option>
                <option value="sif">Sidi-Ifni</option>
                <option value="tan">Tan-Tan</option>
                <option value="trd">Taroudant</option>
                <option value="tiz">Tiznit</option>
              </select>
              <div id="chart" class="chart"></div>
        </div>
    </div>


</body>

<script>
    d = {{ graphJSON | safe }};
    //d.config={staticPlot: true};
    Plotly.newPlot('chart', d, {});

</script>
</html>

Now, I would like to be able to change the day (date) as well. I am confused regarding the modifications to make in order to make this happen. My efforts have, so far, all failed.

Any help/guidance/comment is sincerely appreciated.

0 Answers
Related