Python Flask Jinja SQL:没有值传递给模板

时间:2017-04-11 21:37:14

标签: python sql python-3.x flask jinja2

在我正在研究的Flask函数的GET部分中,我有一些用Python 3编写的非常简单的代码。我试图传入的数据永远不会显示在我的HTML渲染上。

@app.route("/sellselected", methods=["GET", "POST"])
@login_required
def sellselected(order_num):
    if request.method == "POST":
        #not done, just have a redirect to index
    else:
        stock_to_sell = db.execute("SELECT * FROM purchases WHERE order_num = :order_num", order_num=order_num)
        #stock_to_sell = ['fish']

    return render_template("sellselected.html", stock_to_sell=stock_to_sell, order_num=order_num)

SQL语句似乎没有任何传递,它在HTML渲染上只是空白。但作为测试,我也使用'鱼',它也是无/空。

Jinja看起来像:

{% block main %}
<list>
    <ul>{{ stock_to_sell }}</ul>
    <ul>{{ order_num }}</ul>
</list>
{% endblock %}

因此页面正文中包含订单号,但stock_to_sell始终为空。

3 个答案:

答案 0 :(得分:0)

你的问题不再与jinja有关。您的路线错误,应该是:@app.route("/sellselected/<order_num>", methods=["GET", "POST"])

因为你将order_num传递给sellselected函数所以你需要在路由上声明它。

答案 1 :(得分:0)

你说你想把param order_num传递给GET吗?因为代码说POST被重定向到索引。

所以,你将param作为GET传递。你需要先得到它

current_order = request.args.get(&#39; order_num&#39;)

您的代码应为:

@app.route("/sellselected", methods=["GET", "POST"])
@login_required
def sellselected(order_num):
    if request.method == "POST":
        # not done, just have a redirect to index
    else:
        order_num = request.args.get('order_num')
        stock_to_sell = db.execute("SELECT * FROM purchases WHERE order_num = :order_num", order_num=order_num)

return render_template("sellselected.html", stock_to_sell=stock_to_sell, order_num=order_num)

答案 2 :(得分:0)

请注意,如果您遍历一个对象,那么它的内容将返回为空。这是因为结果是一个生成器,它的值只能被访问一次。

无法工作,因为 gcp_certs 已被迭代:

  gcp_certs = connection.execute(query)
  for cert in gcp_certs:
     print(cert.name)
    
  return render_template('certifications.html',
                           gcpcerts=gcp_certs,
                           now=datetime.utcnow(),
                           cookie=token)

作品:

  gcp_certs = connection.execute(query)
  return render_template('certifications.html',
                           gcpcerts=gcp_certs,
                           now=datetime.utcnow(),
                           cookie=token)

一种解决方案:

imports copy

gcp_certs = list(connection.execute(query))
sql_select = ''
for cert in copy.copy(gcp_certs):
     print(cert.name)

return render_template('certifications.html',
                           gcpcerts=gcp_certs,
                           now=datetime.utcnow(),
                           cookie=token)