如何使用Flask创建显示对象属性的表

时间:2015-08-19 22:25:37

标签: python flask sqlalchemy flask-sqlalchemy

我尝试进行搜索,将SQLAlchemy数据库查询的结果显示给我的用户。但是,似乎返回的是一个空列表 - 该表有一个标题但没有其他行。我已经检查过以确保我获得了结果,所以我不知道出了什么问题。我尝试将数据以原始形式和字典列表发送,但仍然没有运气。任何见解?

ORDER BY

的index.html

(
    SELECT pr.ONE, pr.time_of_insertion
    FROM prec pr
    WHERE ...
    ORDER BY pr.time_of_insertion DESC
    LIMIT 10
)
UNION
(
    SELECT hr.TWO, hr.time_of_insertion
    FROM hrec hr
    WHERE ...
    ORDER BY hr.time_of_insertion DESC
    LIMIT 10
)
ORDER BY time_of_insertion DESC
LIMIT 10

1 个答案:

答案 0 :(得分:0)

这是从一些嵌套数据提供html表的快速示例。正如所建议的那样,还有一个带有jsonify数据的额外端点用于调试。

<强> app.py

<ScrollViewer VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst">
    <DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" />
</ScrollViewer>

<强>的index.html

from flask import Flask, render_template, jsonify
import namedtupled as nt  # for debugging 

app = Flask(__name__)

# set up some fake data
foo = { 'system_name': 'foo', 'system_description': 'bar',
        'tags': [{'tag_name': 'happy'}, {'tag_name': 'cat'}],
        'system_date_created': 'today', 'system_hits': 100 }
fuu = { 'system_name': 'fuu', 'system_description': 'bor',
        'tags': [{'tag_name': 'cute'}, {'tag_name': 'puppy'}],
        'system_date_created': 'yesterday', 'system_hits': 99 }

# make fake data classy so it fits your example
results = [nt.map(foo), nt.map(fuu)]  

def refine_results(results):
    """ Refine some search results. """
    # something here, maybe a request for search results
    data = []
    for result in results:
        resultData = {'system_name': result.system_name,
                      'system_description': result.system_description,
                      'system_tags': [tag.tag_name for tag in result.tags],
                      'system_date_created': result.system_date_created,
                      'system_hits': result.system_hits}
        data.append(resultData)
    return data

@app.route('/json')
def data():
    """ Extra endpoint for debugging expected data. """
    searchResults = refine_results(results)
    return jsonify(searchResults)

@app.route('/table')
def table():
    """ html table with data """
    searchResults = refine_results(results)
    return render_template('index.html', searchResults=searchResults)

if __name__ == '__main__':
    app.run(debug=True)