Flask从自动完成中传递选定的值并执行SQL查询以打印结果

时间:2017-07-10 17:25:20

标签: javascript jquery python flask

我是Flask(和Web开发)的新手,我正在尝试从自动完成中获取所选值并将值传递给SQL,最后在html上打印该表。

这是我在html中的javascript

<head>
<script type="text/javascript">
$(function() {
    $("#autocomplete").autocomplete({
        source:function(request, response) {
            $.getJSON("/autocomplete",{
            q: request.term,
            }, function(data) {
            response(data.matching_results);
            });
        },
        minLength: 2,
        select: function(event, ui) {
            alert( "You selected: " + ui.item.label );
            console.log(ui.item.value);
        }
    });
})

</script>
</head>

<body>
<div>
<form class="form-horizontal" method="post" action="/showSelection">
    <h3>Genes</h3>
    <input name="autocomplete" name="inputGene" type="text" placeholder="Gene name" id="autocomplete" class="form-control input-lg"/ >
</form>
</div>
</body>

在我的app.py中(我到目前为止所提出的,(自动完成部分正在运行,但我不知道如何获取值并使用该值来查询SQL)

@app.route('/autocomplete', methods=['GET', 'POST'])
def autocomplete():
    czz = mysql.connect()
    cursor=czz.cursor()
    search = request.args.get('q')
    query = ("SELECT Symbol from drugs where Symbol like '%"+search+"%'")
    cursor.execute(query)
    symbols = cursor.fetchall()
    # query = metadata.query(drugs.Symbol).filter(drugs.Symbol.like('%' + str(search) + '%'))
    results = [mv[0] for mv in symbols]

    return jsonify(matching_results=results)
    czz.close()
    cursor.close()

@app.route('/showSelection', methods=['POST'])
def showSelection():
    pd.set_option('display.max_colwidth', -1)
    _Gene = request.form.get('inputGene')
    # _Gene = request.form['inputGene']
    _Gene = str(_Gene)
    print str(_Gene)
    conn = mysql.connect()
    cursor = conn.cursor()
    query=("SELECT * from tbl_wish where gene_name = %s")%(_Gene)
    cursor.execute(query)
    variant=cursor.fetchall()
    print variant

    vas_dict=[]
    for vas in variant:
        vaf_dict = {
          'Gene':vas[1],
          'Literature':vas[2],
          'Variant':vas[3],
          'Description':vas[4]
         }
         vas_dict.append(vaf_dict)
         variants = pd.DataFrame(vas_dict)
         variants = variants[['Gene','Literature','Variant','Description']]
         #print variants

    return render_template('listVariants.html', tables=[variants.to_html(index=False)], titles=["Variant list"])
    cnn.close()
    cursor.close()

感谢任何帮助!!

2 个答案:

答案 0 :(得分:0)

<强>自动完成

@app.route('/autocomplete', methods=['GET'])
def autocomplete():
    conn = mysql.connect()
    cursor = conn.cursor()
    search = request.args.get('q')
    query = ("SELECT Symbol from drugs where Symbol like '%"+search+"%'")
    cursor.execute(query)
    symbols = cursor.fetchall()
    # query = metadata.query(drugs.Symbol).filter(drugs.Symbol.like('%' + str(search) + '%'))
    results = [mv[0] for mv in symbols]
    cursor.close()
    conn.close()

    return jsonify(matching_results=results)

显示路线

@app.route('/showSelection', methods=['GET', 'POST'])
def showSelection():
    gene = request.form.get('inputGene')  # Returns none if not found in request
    if gene is None:
        flash('gene not found')
        return redirect(url_for('selection view'))  # redirect on input
    conn = mysql.connect()
    cursor = conn.cursor()
    query = ("SELECT * from tbl_wish where gene_name = %s")%(gene)
    cursor.execute(query)
    variant = cursor.fetchall()

    vas_dict = []
    for vas in variant:
        vaf_dict = {
          'Gene':vas[1],
          'Literature':vas[2],
          'Variant':vas[3],
          'Description':vas[4]
        }
        vas_dict.append(vaf_dict)
    cursor.close()
    conn.close()

    return render_template('listVariants.html', variants=vas_dict)

<强> select.html

<head>
<script type="text/javascript">
$(function() {
    $("#inputGene").autocomplete({
        source:function(request, response) {
            $.getJSON("/autocomplete",{
            q: request.term,
            }, function(data) {
            response(data.matching_results);
            });
        },
        minLength: 2,
        select: function(event, ui) {
            alert( "You selected: " + ui.item.label );
            console.log(ui.item.value);
        }
    });
})

</script>
</head>

<body>
<div>
<form class="form-horizontal" method="post" action="/showSelection">
    <h3>Genes</h3>
    <input name="inputGene" type="text" placeholder="Gene name" id="inputGene" class="form-control input-lg"/ >
</form>
</div>
</body>

1)您的输入字段有两个names,它应该只有一个

2)您可以从自动完成路线中删除'POST'方法,因为这是不必要的

3)你需要在路径范围内关闭游标和连接,最好是游标然后连接(即在返回语句之前)

4)您需要在'GET'路线上使用/showSelection方法。

5)你不应该依赖大熊猫来格式化你的表格。这就是Jinja2的用途。

<强> selection.html

{% if variants %}
<table>
    <thead>
    <tr>
        <th>Gene</th>
        <th>Literature</th>
        <th>Variant</th>
        <th>Description</th>
    </tr>
    </thead>
    <tbody>
    {% for variant in variants %}
    <tr>
        <td>variant.Gene</td>
        <td>variant.Literature</td>
        <td>variant.Variant</td>
        <td>variant.Description</td>
    </tr>
    {% endfor %}
</table>
{% else %}
     <p>There are no results</p>
{% endif %}

答案 1 :(得分:0)

我根据您的建议修改了我的代码,由于某种原因,客户端选择的值(自动完成事件)永远不会传递回服务器端。我做了一些谷歌搜索并将这两行添加到我的select:function(

select: function(event, ui) {
            $("#inputGene").val(ui.item.label);
            var getID=ui.item.value;
            return false;
        }

它有效。我现在有一个工作自动完成功能,可以将用户选择的值设置为sql并以html格式打印到表格。

现在我想弄清楚如何在select:fucntion中显示警告消息(当用户选择的值不在DB中时)。目前我可以在app.py中做到这一点(返回到render_template一个erro.html。

最后,我需要使用pandas格式化输出,然后再将它们发送到Jinja打印表。否则,字典列表将无法与Jinja一起使用。我相信还有其他方法可以做到,但我还在学习。

感谢指针