【问题标题】:How to get dropdown list items from pandas dataframe using python flask?如何使用 python 烧瓶从熊猫数据框中获取下拉列表项?
【发布时间】:2019-10-12 09:17:21
【问题描述】:

我需要使用 python flask 将 pandas 数据框中的数据添加到 html 文档的下拉列表中...

@app.route('/api/v1/resources/getservices', methods=['GET'])
def api_services():
    return render_template('view.html',table=df.to_html())


<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Dropdown</title>
     <h1>Services</h1>
</head>
<body>
<select name="table" method="GET" action="/">
  <option value="{{table[0]}}" selected>{{table[0]}}</option>
  {% for colour in table[1:] %}
  <option value="{{colour}}">{{colour}}</option>
  {% endfor %}
</select>
</body>
</html>

我期望的是,熊猫数据框 df 中“服务”列中的数据应作为项目添加到 html 文件的下拉列表中。但每当我尝试使用上述代码时,下拉创建的列表没有任何项目...

【问题讨论】:

  • 前端调试的是什么(例如Chrome中的F12)?
  • python烧瓶和html

标签: python pandas flask dropdown


【解决方案1】:

当您调用to_html() 方法时,它将创建 html 表并且您无法对其进行迭代。我不知道你的 df 数据是什么,但我认为这可能对你有用。

app.py

@app.route('/api/v1/resources/getservices', methods=['GET'])
def api_services():
    d = {'Services': ["red", "green", "blue"]}
    df = pd.DataFrame(data=d)
    return render_template('view.html', table=df)

view.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dropdown</title>
    <h1>Services</h1>
</head>
<body>
<select name="table" method="GET" action="/">
{% for colour in table["Services"] %}
        <option value="{{ colour }}">{{ colour }}</option>
    {% endfor %}
</select>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2021-03-20
    • 2018-09-07
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多