You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask中设置按钮触发/rec路由并传递isbn_index参数

Flask卡片按钮传递ISBN参数到/rec路由方案

这里给你两种实用的配置方案,按需选择:

方案一:表单POST提交(不暴露参数在URL)

在每个书籍卡片里嵌入一个表单,把isbn_index作为隐藏字段,点击按钮时提交到/rec路由。

home.html 代码片段

<!-- 书籍卡片模板 -->
<div class="book-card">
  <!-- 其他书籍信息展示 -->
  <p>ISBN: {{ book.isbn_index }}</p>
  
  <form action="/rec" method="POST">
    <input type="hidden" name="isbn_index" value="{{ book.isbn_index }}">
    <button type="submit" class="btn">Recommendation</button>
  </form>
</div>

app.py 对应路由处理

from flask import request, render_template

@app.route('/rec', methods=['POST'])
def rec():
    # 获取传递的isbn_index参数
    isbn_index = request.form.get('isbn_index')
    # 这里写你的推荐逻辑,比如根据isbn_index查询推荐书籍
    # ...
    return render_template('recommendation.html', isbn=isbn_index, recommendations=...)

方案二:GET链接按钮(参数显示在URL,实现更简单)

把按钮做成带参数的链接,点击时直接跳转到/rec路由并携带isbn_index参数。

home.html 代码片段

<!-- 书籍卡片模板 -->
<div class="book-card">
  <!-- 其他书籍信息展示 -->
  <p>ISBN: {{ book.isbn_index }}</p>
  
  <a href="/rec?isbn_index={{ book.isbn_index }}" class="btn">Recommendation</a>
  <!-- 如果想用按钮样式的链接,也可以这样写 -->
  <button onclick="window.location.href='/rec?isbn_index={{ book.isbn_index }}'" class="btn">Recommendation</button>
</div>

app.py 对应路由处理

from flask import request, render_template

@app.route('/rec', methods=['GET'])
def rec():
    # 获取传递的isbn_index参数
    isbn_index = request.args.get('isbn_index')
    # 推荐逻辑处理
    # ...
    return render_template('recommendation.html', isbn=isbn_index, recommendations=...)

注意点

  • 如果你的推荐操作涉及数据修改,优先用POST方式;如果只是查询推荐内容,GET方式更合适。
  • 记得在rec函数里校验isbn_index的合法性,避免无效参数导致错误。

内容的提问来源于stack exchange,提问作者Amri Rasyidi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:55:25