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)