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

标签 python html flask

我有 2 个像这样的 flask 路线。

@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 调用将返回值的 Flask 路由?

最佳答案

这是因为 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()

关于python - 如何使用 Flask 从 python 调用应用程序路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56064717/

相关文章:

python - 获取 mongoengine 中的第一个对象

python - 自定义 __repr__ 作为从 Enum 派生的类的类方法

python - TypeError : Cannot clone object. 您应该提供 scikit-learn 估计器的实例而不是类

python - 编写 Python 函数来遍历行——接受字符串或类似文件的对象

html - 如何仅向离开图像的文本添加不透明度,而在同一元素中没有任何不透明度?

javascript - 类型错误 : x is undefined

python - Flask 管理员在更改用户模型时覆盖密码

python - Python : list index out of range error

javascript - 在 php 中使用单选按钮值使三个 div 之一出现

python - SqlAlchemy 如何更新所有行的一列数据?