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個不同的值。在
^{pr2}$
一個3rd選項,對于您正在尋找的內容來說,這可能是一個過度的(和/或麻煩的)選項,但為了完整起見,我將提到它。在
可以使用具有可選值的單個路由,然后決定要返回的內容:@app.route('/')
@app.route('/
/')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(最后,我保證)選項是將這兩條路由指向同一個函數,然后使用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)