如何使用Flask从python调用应用程序路由

时间:2019-05-09 17:32:59

标签: python html flask

我有2条这样的烧瓶路线。

@app.route("/table", methods=('GET', 'POST'))
@login_required
def table() -> str:
    return "<table><thead><tr><th>HELLO</th></tr></thead><tbody><tr><td>HOLA</td></tr></tbody></table>"

@app.route('/config', methods=('GET', 'POST'))
@login_required
def config() -> str:
    form = ConfigForm()
    return render_template(
        "product.html",
        form=form)

配置路由会调用ConfigForm,看起来像这样...

class ConfigForm(FlaskForm):
    def __init__(self):
        super().__init__()
        self.table = url_for("table")

由于某种原因,它不包含包含字符串格式html表的self.table,而是包含/table。 是否可以从python调用烧瓶路由,该烧瓶路由会返回值?

1 个答案:

答案 0 :(得分:1)

这是因为url_for返回特定方法的网址字符串(在这种情况下为table

解决方案:创建其他方法

def get_table_content() -> str:
    return "<table><thead><tr><th>HELLO</th></tr></thead><tbody><tr><td>HOLA</td></tr></tbody></table>"

@app.route("/table", methods=('GET', 'POST'))
@login_required
def table() -> str:
    return get_table_content()

@app.route('/config', methods=('GET', 'POST'))
@login_required
def config() -> str:
    form = ConfigForm()
    return render_template(
        "product.html",
        form=form)

然后在下面应该可以工作:

class ConfigForm(FlaskForm):
    def __init__(self):
        super().__init__()
        self.table = get_table_content()