首页 > 解决方案 > 在 Flask 应用程序中将数据从 MySQL 解析为 json 文件

问题描述

我想在我的网站上使用 Bootstrap 表来显示 MySQL 数据库中的数据。我发现了几种显示 Bootstrap 表的方法,其中之一是从 json 文件中获取数据。这里的例子。

将数据从 MySQL 解析为 json 以在 Bootstrap 表中显示数据的最佳方法是什么(我正在使用 Flask)?

下面你可以看到我想用来从 MySQL 获取数据并在我的网站上的 Bootstrap 表中显示的函数

应用程序.py

@app.route('/content_repository', methods=['GET', 'POST'])
def show_data():
# Check if user is loggedin
if 'loggedin' in flask.session:
    search_query = flask.request.form['db'].strip()

    search_query = "('" + ",".join(re.split(r'\W+', search_query)) + "');"

    print(search_query)
    data = sql.execute_query(
        sql.query_select(['ID', 'Create_date', 'Name', 'Region'],
                         from_='product', where='Name in ' + search_query), app_mysql)

    data = json.dumps(data.to_dict('records'))

    return flask.render_template('index.html', username=flask.session['username'], data=data)
# If user is not loggedin redirect to login page
return flask.redirect(flask.url_for('login'))

索引.html

<table
    id="table"
    data-toolbar="#toolbar"
    data-search="true"
    data-show-refresh="true"
    data-show-toggle="true"
    data-show-fullscreen="true"
    data-show-columns="true"
    data-show-columns-toggle-all="true"
    data-detail-view="true"
    data-show-export="true"
    data-click-to-select="true"
    data-detail-formatter="detailFormatter"
    data-minimum-count-columns="2"
    data-show-pagination-switch="true"
    data-pagination="true"
    data-id-field="id"
    data-page-list="[10, 25, 50, 100, all]"
    data-show-footer="true"
    data-side-pagination="server"
    data-url="https://examples.wenzhixin.net.cn/examples/bootstrap_table/data"
    data-response-handler="responseHandler">
</table>

<script>

    var $table = $('#table')

    var data = '{{data}}'; 
    var data = JSON && JSON.parse(data) || $.parseJSON(data);
    $(function() {
        $table.bootstrapTable({data: data})
    })
</script>

标签: pythonmysqlflaskbootstrap-table

解决方案


推荐阅读