【问题标题】:How to send data to another page in FlaskFlask如何向另一个页面发送数据
【发布时间】:2023-02-06 15:39:42
【问题描述】:

我正在使用 Flask 为特定主题创建搜索应用程序,但我遇到了以下消息:

"错误响应 错误代码:414

消息:请求 URI 太长。

错误代码解释:HTTPStatus.REQUEST_URI_TOO_LONG - URI 太长。”

当提交我的索引页面中的表单时,在将 get 请求发送到 api 之前处理数据,并在该行之前进一步处理返回的数据

return redirect(url_for('search',mydict=mydict, mydict2=mydict2, studyset=studyset))

搜索看起来像这样:

def search():
   
    mydict = request.args.get('mydict', type=dict)
    mydict2=request.args.get('mydict2', type=dict)
    studyset=request.args.get('studyset',type=list)

    return render_template('search.html', mydict=mydict, mydict2=mydict2, studyset=studyset)

这里的错误到底是什么?顺便说一句,我正在使用 WTForms,我在 index.html 中指定了方法作为 POST。

【问题讨论】:

    标签: python api flask web-applications


    【解决方案1】:

    您可以使用以下方法将数据发送到另一个页面。

    应用程序.py:

    from flask import Flask, render_template, request, jsonify, url_for, redirect
    
    app = Flask(__name__)
    
    @app.route('/', methods = ['GET', 'POST'])
    def index():
        if request.method == 'POST':
            date = request.form.get('date')
            return redirect(url_for('booking', date=date))
        return render_template('main/index.html')
    
    
    @app.route('/booking')
    def booking():
        date = request.args.get('date', None)
        return render_template('main/booking.html', date=date)    
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    主/index.html:

    <html>
      <head></head>
      <body>
        <h3>Home page</h3>
        <form action="/" method="post">
          <label for="date">Date: </label>
          <input type="date" id="date" name="date">
          <input type="submit" value="Submit">
        </form>
      </body>
    </html>
    
    main/booking.html:
    
    <html>
      <head></head>
      <body>
        <h3>Booking page</h3>
        <p>
          Seleted date: {{ date }}
        </p>
      </body>
    </html>
    

    输出:enter image description here

    enter image description here

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-15
      • 2021-08-21
      • 2014-05-15
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      相关资源
      最近更新 更多