python - Flask BuildError - 无法为端点构建 URL
问题描述
我有一个非常简单的python代码来从我的数据库中选择一些数据
@app.route('/studentsearch', methods = ['POST', 'GET'])
def searchstudent():
""" Displays the student search page for the site """
cursor = mydb.cursor()
cursor.execute ("SELECT * FROM student")
all_students = cursor.fetchall()
cursor.close()
return render_template('studentsearch.html', all_students = all_students)
但是当我去渲染 HTML 页面时,我得到了werkzeug.routing.BuildError: could not build url for endpoint 'studentsearch'。你指的是“newstudent”吗?
我的桌子也很直接......
<table>
<thread>
<tr>
<th>Student ID:</th>
<th>First Name:</th>
<th>Last Name:</th>
<th>Click to View Student Details</th>
</tr>
</thread>
<tbody>
{% for each_result in all_students %}
<tr>
<td>{{ each_result[0] }}</td>
<td>{{ each_result[1] }}</td>
<td>{{ each_result[2] }}</td>
<td>CLICK HERE!!!</td>
</tr>
{% endfor %}
</tbody>
</table>
这是怎么回事?在 python 或 HTML 中甚至没有提到“newstudent”?
根据要求,这里是“newstudent”似乎来自的代码:
def newstudent():
"""Displays the new student page for the site"""
return render_template('newstudent.html')
@app.route('/process_newstudent', methods = ['POST', 'GET'])
def process_newstudent():
""" Processes the data from the new student course """
if request.method == 'POST':
first_name = request.form['firstname']
last_name = request.form['lastname']
year_began = request.form['yearbegan']
try:
cursor = mydb.cursor()
cursor.execute ("INSERT INTO student (first_name, last_name, year_began) VALUES ('{}','{}','{}');".format((first_name.title()), (last_name.title()), year_began))
mydb.commit()
cursor.close()
except mysql.connector.Error as err:
cursor.close()
return failure('newstudent', f"Error message: {err}. Student not added")
else:
cursor = mydb.cursor()
cursor.execute ("SELECT * FROM student")
student_success = cursor.fetchall()
cursor.close()
return render_template('newstudent_success.html', student_success = student_success)
else:
request.method == 'GET'
return render_template('newstudent.html')
解决方案
您是否尝试使用url_for函数在应用程序代码或 HTML 代码中的某处构建动态 URL?
如果是,那么我认为可能发生的情况是您将参数“studentsearch”传递给该函数而不是“searchstudent”(url_for使用视图函数名称构建端点,而不是端点名称)。例如,在 HTML 模板中,有问题的 URL 将像这样构建:
<a href="{{ url_for('searchstudent') }}">Search</a>
推荐阅读
- javascript - 将外部 js 添加到非应用程序项目时,数据路径“”不应具有其他属性(脚本)
- excel - Excel numberformat 不带符号的货币
- jquery - 在每个 HTML 表格行上循环一次
- ios - 如果帐户是通过个人注册创建的,如何启用开发人员资源来创建证书
- influxdb - 在 influxDb 中用不同的 where 子句减去两个计数值
- php - 使用 php 和 mysql 更新某些用户
- java - EmEditor - 如何批量删除我想要的字符?
- javascript - 在 codeigniter 中跟踪函数执行的进度
- eclipse - 没有用于导入 tomcat 的“服务器”选项
- swift - 为什么当我滚动表格视图或集合视图时,集合视图单元格中的数据会发生变化?