Flask视图函数未被调用求助:图书详情跳转功能失效
Flask视图函数未触发及参数传递问题解决
核心问题分析
你的代码存在几个关键错误导致view_book视图无法触发且参数传递失败:
- Flask路由未定义参数,但视图函数要求接收
bookID参数 - HTML表单结构错误,闭合标签顺序颠倒,且用div无法传递表单数据
- 参数获取方式错误,POST请求不应使用
request.args,且语法有误 - HTML模板中变量引用错误,
x[bookID]未正确引用字段名
修正后的代码
1. main.py 修正
from backend import mongo from flask import Flask, render_template, request try: app = Flask(__name__) allbooks = mongo.allbooks rentedBooks = mongo.rentedBooks # 修正拼写错误:rentedBookds → rentedBooks userDB = mongo.userDB @app.route("/") def home(): return render_template('index.html') @app.route('/search', methods=['POST','GET']) def search(): try: if request.method == 'POST': search_data = request.form['search_data'] readResult = mongo.read(allbooks, search_data, "title") return render_template('result.html', content=readResult, specific_value="title") except KeyError as e: print(f"Key Error: {e}") # 处理GET请求或异常情况,返回搜索页面 return render_template('index.html') # 修正路由:添加bookID参数,支持GET/POST请求 @app.route('/view_book/<bookID>', methods=['POST','GET']) def view_book(bookID): try: print("hello world") # 直接使用路由中的bookID参数,无需从请求中二次获取 readResult = mongo.read(allbooks, bookID, "bookID") return render_template('book.html', BookName=readResult) except Exception as e: print(f"Error: {e}") # 异常时返回首页 return render_template('index.html') if __name__ == "__main__": app.run(debug=True) # 开启debug模式,方便开发调试 except TypeError as e: print(f"Type Error: {e}") except TimeoutError: print("Request timed out") except Exception as e: print(f"Error: {e}")
2. 图书结果展示HTML(result.html)修正
<html> <head> <title>搜索结果</title> </head> <body> <form action="/search" method="post"> <input type="text" name="search_data"> <button type="submit">搜索</button> </form> <br> {% for x in content %} <!-- 直接在表单action中携带bookID参数,点击按钮提交请求 --> <form action="/view_book/{{x['bookID']}}" method="post"> <button type="submit">{{x[specific_value]}}</button> </form> <!-- 也可以用更简洁的GET请求方式,直接用a标签跳转 --> <!-- <a href="/view_book/{{x['bookID']}}">{{x[specific_value]}}</a> --> {% endfor %} </body> </html>
关键修改说明
- 路由参数修正:将
/view_book改为/view_book/<bookID>,直接从URL获取参数,避免表单传递的冗余操作,同时修正视图函数名使其更贴合功能。 - 表单结构修复:修正原HTML中表单标签提前闭合的错误,确保按钮在表单范围内,点击时能正确触发请求。
- 参数获取简化:直接使用路由中的
bookID参数,无需从request.form或request.args中重复获取,代码更简洁高效。 - 调试优化:开启Flask的
debug=True,便于开发时实时查看错误信息,快速定位问题。
内容的提问来源于stack exchange,提问作者AVD
相关产品推荐
相关产品推荐

