【问题标题】:Flask post to the same page烧瓶帖子到同一页面
【发布时间】:2016-05-13 13:51:11
【问题描述】:

我有:

 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>

是否可以在烧瓶上创建一个按钮以在同一页面上的烧瓶功能中发布? 谢谢

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    所以您的表单代码可能看起来像这样(这只是一个示例):

    <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="..." 应该是您要发布到的路径。 因此,如果我们想发布到“/”路径,我们可以执行上述操作并使用以下代码在您的代码中捕获它:

    @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':

    来检查它是否是 Post 请求

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多