【问题标题】:Flask variable won't transfer after redirect [duplicate]重定向后烧瓶变量不会转移[重复]
【发布时间】:2019-07-18 07:10:07
【问题描述】:

没有重定向一切正常,但有了这个重定向,似乎没有任何工作。我尝试更新代码,尝试强制 POST 请求,检查大量 SO 帖子,但没有找到适合我的解决方案。

使用 Python 3.7 烧瓶代码:

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/', methods=['POST'])
def num_of_students():
    num = request.form['text']
    return redirect(url_for('test123',num=num))

@app.route('/test123')
def test123():
    return render_template("test.html")



if __name__ == "__main__":
    app.run(debug=True)

HTML 代码 索引:

<!doctype html>
<title>Rubric</title>

<label>Welcome to the Autograding Rubric</label>
<p>Please enter the number of students.</p>
<form method="POST">
    <input type="text", name="text">
    <input type="submit">
</form>        
</html>

测试:

<!DOCTYPE html>
<title>Test</title>
<p>Test Var: {{ num }}</p>

【问题讨论】:

    标签: html python-3.x flask


    【解决方案1】:

    模板没有看到num,因为它不是通过render_template 传递的。试试

    @app.route('/test123')
    def test123():
        num = request.form["text"]
        return render_template("test.html", num=num)
    

    更新:我错过了您重复使用“/”作为路线。 Flask 不会对此感到满意。相反,尝试类似

    @app.route('/', methods=['GET', 'POST'])
    @def index():
        if request.method == 'GET':
            return render_template("index.html")
        num = request.form['text']
        return redirect(url_for('test123'), num=num)
    

    【讨论】:

    • werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'num'
    • 糟糕。那应该是“文本”。上面固定。
    • 同样的错误,但它只是说 text 而不是 num :/
    • 我错过了一个关键细节。请参阅上面的更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 2014-10-14
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多