使用Python的动态表格

时间:2018-08-25 17:32:46

标签: python html flask html-table bootstrap-4

我正在开发一个小型站点,该站点必须从API提取一些数据并将其显示在表中(我不知道需要多少行,这取决于API)。我选择Python作为后端编程语言,并选择Flask作为网络框架。我需要在页面开始时从Python请求API,并将结果显示在HTML模板的表格中。具有某些参数的render_template无法做到这一点-因为它不能动态显示HTML元素,而只能显示文本。没有JS / JQuery或最少使用该怎么办?这是我的表格代码(是Bootstrap 4)

<table class="table table-bordered" id="users">
  <thead>
    <tr>
      <th>ID</th>
      <th>Имя</th>
      <th>Фамилия</th>
      <th>Действие</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td rowspan="1">3319</td>
      <td>Никита</td>
      <td>Морев</td>
      <td><a href="#">Выбрать</a></td>
  </tbody>
</table>

3 个答案:

答案 0 :(得分:4)

您可能还对使用python软件包pandas的这种模式感兴趣:

import pandas as pd

@app.route('/table')
def display_table():
    # do something to create a pandas datatable
    df = pd.DataFrame(data=[[1,2],[3,4]])
    df_html = df.to_html()  # use pandas method to auto generate html
    return render_template('page.html', table_html=df_html)

然后在 page.html 中包含以下内容:

{{ table_html | safe }}

您需要包括 safe 过滤器,以便它呈现原始html而不转义任何字符。

这将呈现以下内容,您还可以使用熊猫中的参数和Styler对其进行样式化。

<table border="1" class="dataframe">  
<thead>    
<tr style="text-align: right;">      
<th></th>    
<th>0</th>      
<th>1</th>    
</tr>  
</thead>  
<tbody>    
<tr>      
<th>0</th>     
<td>1</td>     
<td>2</td>   
</tr>    
<tr>      
<th>1</th>    
<td>3</td>     
<td>4</td>    
</tr> 
</tbody>
</table>

编辑:仅供参考,对于复杂或动态条件格式的问题,如果在python / pandas服务器端更容易设置样式,而不必担心html模板,这也很方便。当然,这取决于您在做什么,但是我认为这在某些情况下(例如我的情况)更容易维护!

答案 1 :(得分:3)

使用Jinja2时,您可以使用Jinja2的脚本功能动态创建表,其语法与Python类似:

proc doSomething {args} {
  # argument checking
  set temp [interp invokehidden {} doSomething {*}$args]
  # result checking
  return $temp
}

在调用render_template时,您需要提供两个变量“ columns”,它们包含行的列列表,而“ item”则包含行。

无需使用JS。

如果要支持某些特殊的数据类型(例如链接),可以通过在模板中使用if语句来实现。

有关更多详细信息,请参见Jinja2的参考: http://jinja.pocoo.org/docs/2.10/templates/

答案 2 :(得分:0)

我已经编辑了@juegern的答案以使用<a>标签,现在我的代码看起来像这样:

<table class="table table-striped" id="users">
 <thead>
  {%- for column in columns %}
     <th>{{ column }}</th>
  {%- endfor %}
 </thead>

 <tbody>
 {%- for row in items %}
    <tr>
    {%- for column in columns %}
        {% if row[column]['link'] %}
            <td><a href="{{ row[column]['link'] }}">{{ row[column]['text'] }}</a></td>
        {% else %}
            <td>{{ row[column] }}</td>
        {% endif %}
    {%- endfor %}
    </tr>
 {%- endfor %}
 </tbody>
 </table>

将一些数据从Flask应用于此表的代码: columns = [{'1': 'Hello', '2': 'World', '3': {'link': '#', 'text': 'Open'}}, {'1': 'World', '2': 'Hello', '3': {'link': '#', 'text': 'Open'}}] return render_template('your_file_name.html', columns=['1', '2', '3'], items=items_list)