烧瓶张贴到同一页 [英] Flask post to the same page
本文介绍了烧瓶张贴到同一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
from flask import Flask, render_template
import datetime
app = Flask(__name__)
@app.route("/")
def hello():
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'HELLO!',
'time': timeString
}
return render_template('main.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
和html:
<!DOCTYPE html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Hello, World!</h1>
<h2>The date and time on the server is: {{ time }}</h2>
</body>
</html>
是否可以在flask上创建一个按钮以在同一页面上发布flask函数? 谢谢
Is possible on flask create a button to post in a flask function on the same page? Thank
推荐答案
因此您的表单代码可以如下所示(这只是一个示例):
<form method='POST' action="/">
<p>username: <input type="text" name="username"/></p>
<p>password: <input type="password" name='password'/></p>
<p><input type="submit" value="Login" style="width: 100px; height: 100px;"/></p>
</form>
action ="..."应该是您要发布到的路径. 因此,如果我们想发布到"/"路径,我们可以执行以下操作,并使用以下代码将其捕获到您的代码中:
action="..." should be the path you want to post to. So if we wanted to post to "/" path we can do the above and catch it in your code by using the following:
@app.route('/', methods=['GET', 'POST'])
def hello():
if request.method == 'POST':
.... # Add whatever code you want to execute if it is a post request
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'HELLO!',
'time': timeString
}
return render_template('main.html', **templateData)
我们需要更改app.route部分,因为我们必须指定我们可以通过Get请求或Post请求到达此路由.我们可以使用 if request.method =='POST':
We need to change the app.route part because we have to specify we can reach this route via a Get request or a Post request. We can check if it is a Post request by using if request.method == 'POST':
希望这会有所帮助.
这篇关于烧瓶张贴到同一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文