【问题标题】:python flask multiple functions don't load in htmlpython烧瓶多个功能不在html中加载
【发布时间】:2021-08-19 17:23:46
【问题描述】:

我正在使用数据框,我需要对其进行一些操作并在网页上显示一个表格。第一个有效,其余无效。我该怎么办? 更新更改路线也不起作用

@app.route('/')
def about():
    return render_template("about.html", result=df.to_html(header='true'))


@app.route('/')
def problem():
    data = df[['attempts', 'activity']]
    data = df.groupby('activity').sum().sort_values('attempts', ascending=False)
    return render_template("about.html", data=data.to_html(header='true'))

这是它的html部分

  <section id="table">
      <h2>table</h2>
      <p class="lead" > {{result | safe}}</p>
  </section>

  <section id="problems">
      <h2>problems</h2>
      <p class="lead" >{{data | safe}}</p>
  </section>

【问题讨论】:

  • 两个端点都指向同一个 url @app.route('/')
  • 我应该在那里写什么?这是一个单页网站,您可以在其中按下按钮并滚动到该部分。写 @app.route('/problems') 什么都不做

标签: python html pandas dataframe flask


【解决方案1】:

我认为你应该遍历数据框,然后尝试显示它。

 <section id="problems">
  <h2>problems</h2>
  {% for d in data%}
  <p class="lead" >{{d | safe}}</p>
  {% endfor %}
  </section>

查看另一个类似问题的答案。希望这个对你有帮助。 How to show a pandas dataframe into a existing flask html table?

【讨论】:

    【解决方案2】:

    您已经定义了具有相同路由的两个端点,因此当您转到“/”时,您只加载一个熊猫。如果您想显示两个数据框,您应该尝试以下操作:

    @app.route('/')
    def about_and_problem():
        data = df[['attempts', 'activity']]
        data = df.groupby('activity').sum().sort_values('attempts', ascending=False)
        return render_template("about.html",about_dataframe=df.to_html(header='true'), problem_dataframe=data.to_html(header='true'))
    

    然后在html中:

     <section id="table">
          <h2>table</h2>
          <p class="lead" > {{about_dataframe | safe}}</p>
      </section>
    
      <section id="problems">
          <h2>problems</h2>
          <p class="lead" >{{problem_dataframe | safe}}</p>
      </section>
    

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多