Flask / Python仅渲染模板中的表

时间:2018-04-18 11:42:07

标签: python html python-2.7 flask

我想在我的网站上使用搜索栏。这将使用用户输入从postgresql数据库获取数据,返回结果并将其显示在表中。

如何将数据发送到我的.py并返回新数据并仅显示包含结果的表格?

我正在使用python 2.7

编辑:

edit_person.html

{% extends "layouts/layout_logged.html"%}

{% block body%}
    <a href="/macro_test" class="btn btn-danger btn-sm my-2 my-sm-0" type="submit">TEST</a>
    <form>
      # here can the user add something from the search results 
    </form>

    {% include "searches/clothings_search_result.html" %}
{% endblock %}

person.py

@app.route('/macro_test', methods=['GET'])
@login_required
def test():
    user_input = request.form["search"]

    search_result = # here the query
    search_result = [dict(r) for r in search_result ]

    result = get_template_attribute('searches/clothings_search_result.html', 'result ')

    return result('search_result')

clothing_search_result.html

{% macro result (search_result) -%}
     {{ search_result[0] }}
     # here is the table i want to render
{%- endmacro %}

1 个答案:

答案 0 :(得分:0)

我找到了一种工作方式。

<强> edit_person.html

{% extends "layouts/layout_logged.html"%}

{% block body%}
    <a id="search_btn" class="btn btn-danger btn-sm my-2 my-sm-0" type="submit">TEST</a>
    <form>
      # here can the user add something from the search results 
    </form>

    <ul id="search_results"></ul>
{% endblock %}

<强> person.py

@app.route('/macro_test/<string:user_input>/debug=<string:debug>', methods=['GET'])
@login_required
    def test(user_input, debug):

        search_query = # here my query

        # get data and make dict
        search_result = sql_conn.query(search_query)
        search_result = [dict(r) for r in search_result]

        # t = true
        # other = false

        if debug == 't':
        # show pretty json
            return jsonify(search_result)
        else:
            # default =  convert all unknown types to str
            return json.dumps(search_result, ensure_ascii=False, default=str)

<强> edit_person.js

$( document ).ready(function() {
    $("#search_btn").click(function()
    {
        $.getJSON( "http://192.168.178.31:8080/macro_test/test/debug=f", function( data ) {

         var items = [];

             $.each( data, function( key, val ) {
                items.push( "<li>" + val.clothes_inventory_number + " - " + val.clothes_date_return +"</li>" );
             });

            $("#search_results").html(items.join( "" ));

        });
    });
});