Home > Software design >  flask app convert sql query to python plotly
flask app convert sql query to python plotly

Time:04-04

i would like to convert in my flask app an SQL query to a plotly pie chart using pandas. this is my code :

def query_tickets_status() :
    query_result = pd.read_sql ("""
            SELECT COUNT(*)count_status, status 
            FROM tickets 
            GROUP BY status""", con = mydc_db)
    return query_result

labels_statut = query_tickets_status['status']
values_statut = query_tickets_status['count_status']

fig = go.Figure(data=[go.Pie(labels=labels_statut, values=values_statut)])
graphSuppliers = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

return render_template('admin/dashboard.html', graphSuppliers = graphSuppliers)

this is my template file.

<html>
 <body>
  <h1>Your Plotly Chart</h1>
  <div id='chart' class='chart'></div>
</body>
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type='text/javascript'>
  var graphs = {{graphSuppliers | safe}};
  Plotly.plot('chart',graphs,{});
</script></html>

but I get error in this line:

labels_statut = query_tickets_status['status']

TypeError: 'function' object is not subscriptable

CodePudding user response:

query_tickets_status is a function but you treat it as list/dictionary/DataFrame.

You have to first use () to execute this function and later use [ ] to get value from dictionary/DataFrame (which this function returns)

result = query_tickets_status()

labels_statut = result['status']
values_statut = result['count_status']

Eventually you could use all directly without creating function query_tickets_status()


query_result = pd.read_sql ("""
        SELECT COUNT(*)count_status, status 
        FROM tickets 
        GROUP BY status""", con = mydc_db)

labels_statut = query_result['status']
values_statut = query_result['count_status']

  • Related