"Method Not Allowed The method is not allowed for the requested URL."

"Method Not Allowed The method is not allowed for the requested URL."

我已经通读了这个问题的相关帖子,但没有找到修复或似乎匹配的答案(如果我错过了,我深表歉意,我浏览了大约 10 篇帖子)。

正在编写一个在数据库中查找条目的搜索页面。最初我把它写成两个独立的函数。一个显示搜索框,第二个进行实际搜索和 return 结果。这很好用,但我试图通过将搜索框保持在页面顶部并 return 搜索结果(如果有的话)来使它更 "user friendly"。

看起来很简单,但行不通。

Python views.app

中的代码
@app.route('/search', methods=['POST'])
def SearchForm():

    if request.method == "POST":
        output = []
        searchterm = request.form['lookingfor']
        whichName = request.form['name']
        if searchterm:
            conn = openDB()
            results = findClient(conn, searchterm, whichName)
            for r in results:
                output.append({'id': r[0], 'fname': r[1], 'lname': r[2], 'phonen': r[3], 'email': r[4], 'started': r[5],
                               'opt': r[6], 'signup': r[7], 'enddate': findEndDate(r[7], r[5])})
            closeDB(conn)
            if output:
                message = "Record(s) Found"
            else:
                message = "Nothing found, sorry."
            return render_template('search.html', message=message, output=output)
        else:
            output = []
            message = "Please enter a name in the search box"
            return render_template('search.html', message=message, output=output)
    else:
        return render_template('search.html')

HTML 对于 search.html

{% extends "baseadmin.html" %}
{% block content %}
<div>
    <form action="{{url_for('search')}}" method="post">
        <p>Search for a Client: <input type="text" name="lookingfor"/></p>
        <input type="radio" name="name" value="fname" id="fname"><label for="fname">First Name</label>
        <input type="radio" name="name" value="lname" id="lname"><label for="lname">Last Name</label>
        <input type="submit" value="submit"/>
    </form>
</div>
<h2>{{ message }}</h2>
<div>
    <table>
      <tr>
        <th>Name</th>
        <th>Email Address</th>
        <th>Phone Number</th>
        <th>Trial Method</th>
        <th>Start Date</th>
        <th>EndDate</th>
      </tr>
      {% for client in output %}
        <tr>
          <td>{{ client['fname'] }} {{ client['lname'] }}</td>
          <td>{{ client['email'] }}</td>
          <td>{{ client['phonen'] }}</td>
          <td>{{ client['started'] }}</td>
          <td>{{ client['signup'] }}</td>
          <td>{{ client['enddate'] }}</td>
        </tr>
      {% endfor %}
    </table>
</div>
{% endblock %}

正如@dirn 在他的 中已经提到的,@app.route('/search', methods=['POST']) 中的 methods=['POST'] 表示函数 SearchForm 和 URL '/search'将只接受 POST 个请求。如果有人试图仅使用 URL 访问该页面,他们将使用 GET 请求来访问该页面。

将行更改为 @app.route('/search', methods=['GET', 'POST']) 应该可以修复错误。

(回答主要是为了 (1) 显示完整的解决方案和 (2) 使 可见。)