您好我是python flask的新手,我有一个400错误请求错误的简单问题,这应该是由于在尝试将它们传递给python烧瓶中的函数时在表单中错误地命名了变量。我做了一些研究,但我仍然无法弄清楚我的代码出错了,任何帮助都会非常感激。 这是html表单的代码
<html>
<body>
<h1>Add a Munroe to your list</h1>
<form action = "{{ url_for('addmunro') }}" method="POST"
enctype = "multipart/form-data">
Name<br>
<input type="text" name="mnName"/><br>
Description<br>
<input type="text" name="mnDesc"/><br>
Region<br>
<input type="text" name="mnRegion"/><br>
Height<br>
<input type="text" name="mnHeight"/><br>
Walk date<br>
<input type="text" name="mnDate"/><br>
Walk image<br>
<input type="text" name="mnImage"/><br>
<br>
<br>
<input type="submit" name="add-munro.html" value = "ADD MUNRO"/>
</form>
</body>
</html>
这是python flask应用程序的代码
from flask import Flask, render_template, url_for, redirect, json, request
app = Flask(__name__)
@app.route('/add-munro.html', methods=['GET'])
def addmunro():
#Create an empty list
mnList={}
#Create a munro dictionary
munro = {'name':request.form['mnName'],
'desc':request.form['mnDesc'],
'region':request.form['mnRegion'],
'height':request.form['mnHeight'],
'date':request.form['mnDate'],
'image':request.form['mnImage']}
#the munro dictionary is added to mnList
#mnList.append(munro)
return render_template('add-munro.html')
if __name__ == "__main__":
app.run(host = '0.0.0.0', debug = True)
答案 0 :(得分:1)
您在表单中提出了POST
个请求,但只允许在您的应用路由中使用GET
方法。将@app.route('/add-munro.html', methods=['GET'])
更改为@app.route('/add-munro.html', methods=['POST'])
。
答案 1 :(得分:0)
有几个错误:
我已经更新了这些内容,现在很高兴:
application.py
from flask import Flask, render_template, request, url_for
app = Flask(__name__)
@app.route('/add-munro', methods=['GET','POST'])
def addmunro():
if request.method == "POST":
#Create an empty list
mnList={}
#Create a munro dictionary
munro = {'name':request.form['mnName'],
'desc':request.form['mnDesc'],
'region':request.form['mnRegion'],
'height':request.form['mnHeight'],
'date':request.form['mnDate'],
'image':request.form['mnImage']}
return render_template('add-munro.html', munro=munro)
else:
return render_template('add-munro.html')
if __name__ == '__main__':
app.run(debug=True)
add-munro.html
<html>
<body>
{% if munro is defined -%}
<h3>
Name: {{ munro.name }}
</h3>
<h3>
Description: {{ munro.desc }}
</h3>
<h3>
Region: {{ munro.region }}
</h3>
<h3>
Height: {{ munro.height }}
</h3>
{%- endif %}
<h1>Add a Munroe to your list</h1>
<form action = "{{ url_for('addmunro') }}" method="POST"
enctype = "multipart/form-data">
Name<br>
<input type="text" name="mnName"/><br>
Description<br>
<input type="text" name="mnDesc"/><br>
Region<br>
<input type="text" name="mnRegion"/><br>
Height<br>
<input type="text" name="mnHeight"/><br>
Walk date<br>
<input type="text" name="mnDate"/><br>
Walk image<br>
<input type="text" name="mnImage"/><br>
<br>
<br>
<input type="submit" value = "ADD MUNRO"/>
</form>
</body>
</html>
输出: