首页 > 解决方案 > 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')

标签: pythonhtmlflask

解决方案


您是否尝试使用url_for函数在应用程序代码或 HTML 代码中的某处构建动态 URL?

如果是,那么我认为可能发生的情况是您将参数“studentsearch”传递给该函数而不是“searchstudent”url_for使用视图函数名称构建端点,而不是端点名称)。例如,在 HTML 模板中,有问题的 URL 将像这样构建:

<a href="{{ url_for('searchstudent') }}">Search</a>

推荐阅读