首页 > 解决方案 > 如何使用 Flask 从 python 调用应用程序路由

问题描述

我有 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")

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

标签: pythonhtmlflask

解决方案


这是因为url_for返回特定方法的 url 字符串(在这种情况下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()

推荐阅读