从 Dash 框架中的输入字段中检索值

Retrieve value from Input field in Dash Framework

我是 Dash 框架的新手。请帮帮我。 我有输入字段,但我不知道如何检索用户输入的值。 当检索到该值时,我必须在我的 SQL table 中搜索该值,然后如果存在则以表格格式显示具有该值的所有行。 我也不知道如何使用 SQL 来做这些事情。

请帮忙。

这是我的代码片段:

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import mysql.connector

db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  db="trial"
)

cursor = db_connection.cursor()

df = pd.read_sql("select * from merge where ProductName=%s", db_connection,'Wine')

def generate_table(dataframe):
   return html.Table(className='hellob',
      # Header
      children=[html.Tr([html.Th(col) for col in dataframe.columns])] +
      # Body
      [html.Tr([
         html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
      ]) for i in range(len(dataframe))]
   )
    
app = dash.Dash()
app.layout = html.Div(children=[
   html.H4(children='Sales Of February 2020 by MHD'),

   html.Label('Product Name: '),
   dcc.Input(
       id='tfield',
       placeholder='Input the product name',
       type='text'
       ),
   generate_table(df)
])

if __name__ == '__main__':
   app.run_server(debug=False)

现在的代码是 运行 但是从我的数据库中给出整个 table 我只需要那些 ProductName 与用户输入匹配的行。

   app.layout = html.Div(children=[
   html.H4(children='Sales Of February 2020 by MHD'),

   html.Label('Product Name: '),
   dcc.Input(
       id='tfield',
       placeholder='Input the product name',
       type='text'
       ),
   generate_table(df)
])

@app.callback(Input('tfield', 'value'))
def callback(input_value):
    return input_value

这也不适用于输入文本值 我也想存储和使用输入的值。

帮我解决这个问题。

发送参数的语法是你的情况

df = pd.read_sql("select * from merge where ProductName=%s", db_connection, params=("Wine",))

您必须根据用户输入将 Datafrane 过滤为 selectolny

df.filter(like='Chardonnay', axis=0)

而不是 'Chardonnay' 你输入破折号。

每个元素都必须有其 唯一 ID,因此您也应该将其添加到您的 dcc.Input

我已经自己解决了我的问题 这是解决方案:

app = dash.Dash()
app.layout = html.Div(children=[
   html.H4(children='Sales Of February 2020 by MHD'),
   html.Label('Product Name: '),
   dcc.Input(
       id='tfield',
       placeholder='Input the product name',
       type='text'
       ),
   html.Br(),html.Br(),
   html.Div(id='my-output'),
])

@app.callback(Output('my-output','children'),[Input('tfield', 'value')])
def callback(input_value):
   df = pd.read_sql("select * from merge where ProductName=%s", db_connection,params= 
        (input_value,))
    return generate_table(df)