用Python 2.7s Flask尝试了几个小时来实现这个目标:
site.com/diseases : gives a page where I can list all diseases
site.com/diseases/diseaseX : list of subtopics for diseaseX
site.com/diseases/diseaseX/subHeading : so a url can be shared that brings users to a specific subheading e.g. overview, causes
app.py
from flask import Flask, render_template
app = Flask(__name__)
app.route('/home')
def home(): render_template('home.html')
@app.route('/diseases/<disease>/<subheading>')
def diseases(disease=None, subheading=None):
return render_template('diseases.html', disease='new')
app.run(debug=True)
路由需要变量或给出404错误。参数默认值已更改为&#39;疾病&#39; &安培; &#39; sub&#39;,但加载site.com/diseases也会给出404。仅添加变量,例如site.com/diseases/diabetes/treatment有效,但如果有人只输入site.com/diseases或site.com/diseases/diabetes怎么办?我无法找到任何人这样做的例子,每个人只是陈述所需的变量,然后遵守它们,所以这可能是一个不理解标准Web应用程序的问题。理想情况下,URL可以扩展到任何长度,例如/疾病/糖尿病/治疗/治疗X,但我有点迷失方向。
EDIT 我做了
取得了进展@app.route('/diseases/<path:queries>)
路径:元素将任何/视为文本,所以我现在可以
/diseases/diabetes/treatment/treatmentX
并在函数中执行
queries.split('/')
获取离散的URL部分。这似乎有点长篇大论,但也许它是如何完成的?
答案 0 :(得分:1)
您可以定义到同一功能的多条路线,并在路线定义中设置默认值。这是我的建议:
@app.route('/diseases', defaults={'disease': None, 'subheading': None})
@app.route('/diseases/<str:disease>/<str:subheading>')
def diseases(disease, subheading):
return render_template('diseases.html', disease='new')