已经尝试了几个小时用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错误。参数默认值已更改为“疾病”和“子”,但加载site.com/diseases也会提供404。仅添加变量,例如site.com/diseases/diabetes/dialysis有效,但是如果有人只输入site.com/diseases或site.com/diseases/diabetes怎么办?我找不到任何人这样做的例子,每个人都只是陈述了必需的变量,然后服从它们,所以也许这是一个不了解标准Web应用程序过程的问题。理想情况下,URL可以扩展为任意长度,例如/ diseases / diabetes / treatment / treatmentX,但是我对如何操作有些迷失。

编辑
我已经做到了

@app.route('/diseases/<path:queries>)


path:元素将任何/视为文本,因此我现在可以

/diseases/diabetes/treatment/treatmentX


并在函数中

queries.split('/')


以获得离散的URL部分。这似乎有些漫长,但是也许是这样完成的?

最佳答案

您可以为同一功能定义多个路由,并在路由定义中设置默认值。这是我的建议:

@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')

10-07 17:50