首页 > 解决方案 > 将数据从 jinja 取回 Flask?

问题描述

我现在拥有的是显示的成分列表,如下所示:

{% block content %}

<form method="POST">
    <h1>DATA</h1>
    {% for c in data %}
    <h1>{{ c.i_id }} {{ c.name }}</h1>
    {% endfor %}
</form>
{% endblock %}

我遇到的问题是将每个项目显示为可点击,让用户单击一个并将其添加到数据库表“userIngredients”中,其中包含值u_idi_id. u_id已经存储在 上session['u_id'],但是,i_id这是我试图从可点击项目中检索的内容,因此我可以在每次点击时完成以下查询:'INSERT INTO userIngredients VALUES(%s,%s)',(session[u_id],i_id)

@app.route('/addingredients', methods=['GET','POST'])
def addingredients():
    c = sq.connection.cursor()
    result = c.execute('SELECT * FROM Ingredients')
    data = c.fetchall()
    return render_template('user/addIngredients.html', data=data)

标签: htmlformsflaskjinja2

解决方案


只需为此使用常规 HTML。

<a href="/addingredients/{% session['u_id'] %}/{% c.i_id %}">{{ c.i_id }} {{ c.name }}</a>

单击此按钮应触发对端点的响应,您可以在其中使用以下代码将其添加到数据库中

@app.route('/addingredients/<user_id>/<ingredient_id>')
def add_ingredients(user_id, ingredient_id):
    # Important to cast the strings here to integers
    # both as protection from SQL injection and to make sure
    # the values are inserted as actual integers
    user_id = int(user_id)
    ingredient_id = int(ingredient_id)
    c = sq.connection.cursor()

    c.execute('INSERT INTO userIngredients VALUES(%s,%s)', (user_id,ingredient_id))

    # Then if you want, you can re-render the template
    result = c.execute('SELECT * FROM Ingredients')
    data = c.fetchall()
    return render_template('user/addIngredients.html', data=data)

我会将渲染移动到与 不同的端点/addingredients,因为名称与模板并不真正适合。如果可以的话,我建议使用 RESTful/ingredients/add添加新成分并/ingredients获取所有成分的列表,或者/getingredients/addingredients同样的事情


推荐阅读