Flask - POST Error 405 Method Not Allowed

2019-01-17 09:11发布

I'm just starting to learn Flask, and I am trying to create a form which will allow a POST method. Here's my method:

@app.route('/template', methods=['GET', 'POST'])
def template():
    if request.method == 'POST':
        return "Hello"
    return render_template('index.html')

And my index.html:

<html>
  <head>
    <title> Title </title>
  </head>
  <body>
    Enter Python to execute:
    <form action="/" method="post">
      <input type="text" name="expression" />
      <input type="submit" value="Execute" />
    </form>
  </body>
</html>

Loading the form (rendering it when it receives GET) works fine. When I click on the submit button however, I get a POST 405 error Method Not Allowed. Why isn't it displayed Hello?

3条回答
趁早两清
2楼-- · 2019-01-17 09:54

Your form is submitting to / when the method is routed for /template unless that is a typo, you should adjust your form's action attribute to point at the template view: action="{{ url_for('template') }}"

查看更多
We Are One
3楼-- · 2019-01-17 09:57

Replace:

 <form action="/" method="post">

with:

 <form action="{{ url_for('template') }}" method="post">
查看更多
在下西门庆
4楼-- · 2019-01-17 10:11

If you omit the action attribute, the form will post to the current URL.

Replace:

<form action="/" method="post">

with:

<form method="post">
查看更多
登录 后发表回答