首页 > 解决方案 > 为什么我的函数重定向而不在 Flask 中传递数据

问题描述

我正在尝试创建烧瓶应用程序,将我的 DNA 转换为 RNA。但我无法使用重定向传递数据。这里有什么问题?

蟒蛇代码:

@app.route('/', methods=['GET','POST'])
def home():
    form = DNAForm()
    if form.validate_on_submit():
        # flash(f'Your dna is {form.dna.data.Upper()}', 'success')
        dna = form.dna.data.upper()
        rna = dna.maketrans('ACGT','UGCA')
        return redirect(url_for('home', rna=rna))
    return render_template('index.html', form=form)

html代码:

{% if rna %}
   <h4>The RNA is: <span class="text-danger">{{ rna }}</span> </h4>
{% endif %}

标签: python-3.xflask

解决方案


当您进行重定向时,它将返回:

return render_template('index.html', form=form)

所以rna不会传给index.html

这是解决方法

@app.route('/', methods=['GET','POST'])
def home():
    form = DNAForm()
    rna = None
    if form.validate_on_submit():
        dna = form.dna.data.upper()
        rna = dna.maketrans('ACGT','UGCA')
        # if you don't want the form to be filled with previous data
        form.dna.data = ''

    return render_template('index.html', form=form, rna = rna)

现在,当form被提交和验证时,它将给出rna一些显示的价值index.html


推荐阅读