✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
📊 Dash 2.0 is Arriving. Register here.

Dropdown of table names from a database

I’m trying to get my table_names from my database and make it as dropdown where I can click on it to show each tables graph but I don’t know how to call it.

I made this code but it comes out with this error
options=[{‘label’: i, ‘value’: i} for i in df.b.unique()]
NameError: name ‘df’ is not defined

can somebody tell me what I did wrong?
P.s : I’m a complete beginner in Python and coding in general.

import dash
import dash_core_components as dcc
import dash_html_components as html

import pandas as pd

import csv
import MySQLdb

import plotly.plotly as py
import plotly.graph_objs as go



conn = MySQLdb.connect(host='127.0.0.1', user='user', passwd='pass', db='road')
cursor = conn.cursor()

app = dash.Dash()

app.layout = html.Div([
    dcc.Dropdown(
        id='dropdown',
        options=[{'label': i, 'value': i} for i in df.unique()],
        value='x',
        clearable=False
    ),
    html.Div(id='graph-container')
])


@app.callback(
    dash.dependencies.Output('graph-container', 'children'),
    [dash.dependencies.Input('dropdown', 'value')])
def sql(value):
    dff = pd.read_sql(
        'SELECT * FROM  "{}"'.format(value),conn
        )
    return {
        'data': [
                    go.Scatter(
                        x=dff['time'],
                        y=dff['strain'],
                        mode='lines',
                        
                        ),
                ],
        'layout': go.Layout(

                    xaxis=dict(
        #               type='line',
                        title='Time(s)',
                        showgrid=True,
                        #zeroline=True,
                        showline=True,
                    ),
                    yaxis=dict(
                        title= 'Microstrain',
                        showgrid=True,
                        #zeroline=True,
                        showline=True,
                    ),
                    showlegend=False,
                )
        }


if __name__ == '__main__':
    app.run_server(debug=True)
1 Like

Exactly what it says. Variable df does not exist in the scope where it is called. You first have to create and initialize variable df before accessing it in

app.layout = html.Div([
    dcc.Dropdown(
        id='dropdown',
        options=[{'label': i, 'value': i} for i in df.unique()],
        value='x',
        clearable=False
    ),
    html.Div(id='graph-container')
])

What is it supposed to be?