我正在嘗試創建一個動態燒瓶路線。我想為我的路由創建一個并行頁面,內部用戶在 URL 前添加“vo/”時可以看到該頁面。所以基本上有兩種不同的路線/vo/feedbackform和/feedbackform。我知道我可以在應用程式中創建兩條路線,但我希望我可以優化。
@app.route('/<x>feedbackform', methods=['GET', 'POST'])
def feedback_portal(x):
if x == 'vo/':
return render_template('feedback_vo.html', title='Inquiry Submission')
elif x == '':
return render_template('feedback.html', title='Inquiry Submission')
到目前為止,這僅在x我的 URL 部分中使用 vo/ 的 URLelif不起作用并且出現錯誤時才有效。
uj5u.com熱心網友回復:
我不認為這是 Flask 支持的。
對于您只有 2 條路徑支持的情況,您可以將兩個裝飾器/路由添加到同一個函式,然后檢查request.path以呈現適當的模板:
from flask import request
@app.route('/vo/feedbackform', methods=['GET', 'POST'])
@app.route('/feedbackform', methods=['GET', 'POST'])
def feedback_portal():
if request.path[0:4] == '/vo/':
return render_template('feedback_vo.html', title='Inquiry Submission')
else:
return render_template('feedback.html', title='Inquiry Submission')
如果您有多個選項來支持而不是僅支持/vo/,則可以考慮將動態部分宣告為path:
@app.route('/<path:x>feedbackform', methods=['GET', 'POST'])
并添加另一條路線來處理 static /feedbackform。
uj5u.com熱心網友回復:
基于@ilias-sp 的回答,我可以使用以下代碼:
@app.route('/feedbackform/', methods=['GET', 'POST'], defaults={'x': None})
@app.route('/<x>/feedbackform/', methods=['GET', 'POST'])
def feedback_portal(x):
if x=='vo':
return render_template('feedback_vo.html', title='Inquiry Submission')
elif x==None:
return render_template('feedback.html', title='Inquiry Submission')
uj5u.com熱心網友回復:
我不知道你想要一個處理程式的原因,但如果你提供的代碼片段就是它的全部內容,我看不出兩條路線之間有太多共同點來保證一個處理程式,特別是如果你打算使用 if-else 以不同方式處理每種情況。
我寧愿有單獨的路線 - 它更清晰且不那么復雜(恕我直言)。
@app.route('/feedbackform/', methods=['GET', 'POST'])
def feedback_portal():
return render_template('feedback.html', title='Inquiry Submission')
@app.route('/vo/feedbackform/', methods=['GET', 'POST'])
def feedback_portal_vo():
return render_template('feedback_vo.html', title='Inquiry Submission')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526739.html
標籤:Python烧瓶
上一篇:socket.io中的房間是否會在一段時間后自動洗掉?
下一篇:燒瓶顯示上傳的CSV檔案的形狀
