![](/img/trans.png)
[英]Can you return a function in flask as well as return render_template?
[英]Flask render_template with function return
我最近正在研究Flask。 而且我有一个问题。
我的脚本如下所示:
@app.route('/')
def index():
// execute
return render_template('index.html', body=body, block=block)
@app.route('/api/')
def api():
// execute
return 'api'
函数api
和index
完全相同。
我认为是要创建一个两个页面都可以调用并表示相同内容的函数。
有没有可能实现这一目标的方法?
TL; DR在这种情况下,我想我会选择使用我提出的第 4 个选项
我将介绍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)
第三种选择,对于您正在寻找的东西可能看起来像是过分(和/或笨重),但是为了完整起见,我会提到它。
您可以使用带有可选值的单个路由,然后确定要返回的内容:
@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
第四个 (最后一个,我保证)选项是将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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.