我刚刚开始学习Flask,我正在尝试创建一个允许POST方法的表单。
这是我的方法:
@app.route('/template', methods=['GET', 'POST'])
def template():
if request.method == 'POST':
return("Hello")
return render_template('index.html')
而我的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>
加载表单(在收到GET时呈现它)工作正常。当我点击提交按钮时,我得到一个POST 405 error Method Not Allowed
。
为什么不显示“你好”?
当方法被路由为/
时,您的表单将提交给/template
,除非这是一个拼写错误,您应该调整表单的action
属性以指向template
视图:action="{{ url_for('template') }}"
更换:
<form action="/" method="post">
有:
<form action="{{ url_for('template') }}" method="post">
如果省略action
属性,表单将发布到当前URL。
更换:
<form action="/" method="post">
有:
<form method="post">