我一直在使用python flask和html,为了创建一个小网站,(就像我离开学校一样的业余爱好),我用html创建了一个表单并保存了它在项目的templates文件夹中。然后我还在python脚本中添加了一个函数,所以当单击一个按钮时,它会将用户重定向回主页(index.html),但是当我测试了网页并点击了该按钮时网页(烧瓶服务器运行)" 400错误请求"页面显示
Python代码:
#Python code behind the website
import datetime
from flask import Flask, session, redirect, url_for, escape, request, render_template
print ("started")
def Log(prefix, LogMessage):
timeOfLog = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S" + " : ")
logFile = open("Log.log", 'a')
logFile.write("[" + timeOfLog + "][" + prefix + "][" + LogMessage + "] \n")
logFile.close()
app = Flask(__name__)
@app.route('/')
def my_form():
print ("Acessed index")
return render_template("index.html")
@app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']#requests text from the text form
processed_text = text #does nothing
user = "" #use poss in future to determin user
logFile = open("MessageLog.msglog", 'a')#opens the message log file in append mode
logFile.write(text + "\n")#stores the inputted message in the message log file
logFile.close()
#print (text)
Log("User Message", (user + text))#uses the main log file to store messages aswell as errors
print ("Accessing index")
return render_template("test.html")
@app.route('/test', methods=['POST'])
def test():
#text = request.form['text']
print ("Test page function")
#return "hello"
return render_template("index.html")
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0')
HTML代码: - >
<body>
<h1>Test Page</h1>
<form method="POST">
<input type="submit" name="my-form" value="Send">
</form>
</body>
Stack Track:
答案 0 :(得分:1)
您需要将表单发布到正确的网址:
<body>
<h1>Test Page</h1>
<form method="POST" action='/test'>
<input type="submit" name="my-form" value="Send">
</form>
</body>
默认情况下,如果您没有向HTML表单添加action
属性,则只会将其定义为您当前所在网址的定义方法。您可以添加action
属性来更改该行为。
您也可以使用url_for()
功能执行此操作。这有点安全,因为URL往往比您的查看方法名称更频繁地更改:
<body>
<h1>Test Page</h1>
<form method="POST" action="{{ url_for('test') }}">
<input type="submit" name="my-form" value="Send">
</form>
</body>
将视图方法的名称(不是它的URL)作为字符串传递给函数。小心使用正确的引号。
请注意,同一网址有2个视图会让人感到有些困惑。通常这样的事情虽然是YMMV,但是考虑到你的应用:
@app.route('/someurl')
def some_view():
if request.method == "POST":
# handle POST
else:
# handle GET