【问题标题】:How to pass two variables to a function with decorator如何使用装饰器将两个变量传递给函数
【发布时间】:2020-01-05 18:42:36
【问题描述】:

我有一个函数('postcode'),它接受用户的输入并生成两个我想传递给另一个函数('constituency')的变量。

如何在函数之间传递两个参数,以便只将一个参数传递给 url?

app("/postcode", methods=["GET", "POST"])
def postcode():
    form = PostcodeForm()
    if form.validate_on_submit():        
        pc = form.postcode.data.replace(" ", "").strip()
        if validate(pc) == True:
            code, const = dosomething(pc)
            return redirect(url_for('app.constituency', const_id=const)), code

    return render_template("template1.html", form=form)


@app.route("/constituency/<string:const_id>")
def constituency(const_id):
    const = const_id
    people = People.query.filter_by(code=code) # I want the value of "code" here to come from the function 'postcode' above
    return render_template("template2.html", people=people, const=const)

【问题讨论】:

    标签: python flask decorator


    【解决方案1】:

    您要么需要将code 作为查询参数传递,要么创建一个带有code 参数的新url 路由,url_for 不会直接调用consitutency,它只是生成浏览器的url然后请求。

    【讨论】:

    • 谢谢。我发现我可以将 'code' 设为全局变量:global code code, const = geolocate(pc) 我认为这可能是一个更优雅的解决方案。
    • 这不是很优雅,一个可能的解决方案是将代码保存在cookie中
    猜你喜欢
    • 1970-01-01
    • 2018-09-11
    • 2010-12-30
    • 1970-01-01
    • 2021-11-15
    • 2021-08-20
    • 2021-11-21
    • 2016-02-14
    • 1970-01-01
    相关资源
    最近更新 更多