html - 将数据从 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_id
和i_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)
解决方案
只需为此使用常规 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
同样的事情
推荐阅读
- python - Django 格式错误的 views.py 或 urls.py(编辑器应用程序)
- angular - 由于 SassError 导致 ng 测试失败:找不到要导入的样式表
- r - Rcpp:这是使用 Rcpp 修改数据框某些列的最佳方法
- twitter-bootstrap - 尝试复制 Bootstrap Carousel 示例... Carousel 的一部分被导航栏隐藏
- java - android加速度计中加速度的双积分
- css - 单击按钮后如何在 Ionic 5 上添加动画?
- regex - 正则表达式验证以逗号分隔的唯一电子邮件地址列表
- python - 读取具有多个分隔符的文件
- shopify - Shopify:在购物车中按产品标签隐藏结帐按钮
- mysql - RDS 代理会影响当前的应用程序端池吗?