【问题标题】:Flask render_template with function return带有函数返回的烧瓶渲染模板
【发布时间】:2017-11-26 11:44:36
【问题描述】:

我最近在 Flask 上工作。 我有一个问题。

我的脚本如下所示:

@app.route('/')
def index():
    // execute
    return render_template('index.html', body=body, block=block)
@app.route('/api/')
def api():
    // execute
    return 'api'

函数apiindex 做同样的事情。

我的想法是创建一个两个页面都可以调用的函数,并代表相同的东西。

有没有可能实现的方法?

【问题讨论】:

  • 我不明白你的问题 - 请你详细说明

标签: python flask


【解决方案1】:

TL;DR在这种情况下,我想我会选择使用我提出的第 4th 选项

我将介绍 4 个选项,其中一些可能比其他选项更可行。

如果您担心execute 表示的代码的代码重复 (DRY),您可以简单地定义一个两个路由都可以调用的函数:

def execute():
    # execute, return a value if needed
    pass

@app.route('/')
def index():
    execute()
    return render_template('index.html', body=body, block=block)

@app.route('/api/')
def api():
    execute()
    return 'api'

这可能就是你想要的。

然而,如果你想为同一个函数提供两条路径,你也可以这样做,只要记住它们是从上到下扫描的。显然,您不能使用这种方法返回 2 个不同的值。

@app.route('/')
@app.route('/api/')
def index():
    # execute
    return render_template('index.html', body=body, block=block)


一个 3rd 选项,对于您正在寻找的东西来说,这可能看起来有点矫枉过正(和/或繁琐),但为了完整起见,我会提到它。

您可以使用带有可选值的单个路由,然后决定要返回的内容:

@app.route('/')
@app.route('/<path:address>/')
def index(address=None):
    # execute
    if address is None:
        return render_template('index.html', body=body, block=block)
    elif address == 'api':
        return 'api'
    else:
        return 'invalid value'  # or whatever else you deem appropriate


第 4th (也是最后一个,我保证)选项是将 2 条路由定向到同一个函数,然后使用 request 对象查找客户端请求的路由:

from flask import Flask, request

@app.route('/')
@app.route('/api')
def index():
    # execute
    if request.path == '/api':
        return 'api'
    return render_template('index.html', body=body, block=block)

【讨论】:

  • 函数execute的返回值可以在模板中渲染吗?
  • @james50428 任何东西都可以渲染,由你在模板中正确渲染。
  • 哦,我明白了。我忘了声明我的返回值 LOL
  • 感谢您的详细回答。对不起我糟糕的英语:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 2015-05-08
相关资源
最近更新 更多