获取Flask功能的路线列表

时间:2014-02-23 19:51:01

标签: python twitter-bootstrap dynamic flask

我正在使用Flask和Bootstrap 3,我想获得一个函数生成的所有url的列表,以便我可以在bootstrap主题中链接到所有这些urls。

e.g:

/programme/23022014
/programme/24022014
/programme/25022014

这是我的功能:

@cache.cached(timeout=86400)
@app.route('/programme/<prog_id>')
def programme(prog_id):
    daily_bands= my_location + "/static/data/bandsdaily/"  + prog_id  + ".json"
    event_details = []
    with open(daily_bands) as f:
            for line in f:
                data = json.loads(line)
            event_details.append(data)
    return render_template('index.html', data=event_details) 

我尝试使用prog_id变量并使用render_template传递它,它不起作用,我尝试使用url_for()但我认为后者用于其他目的。

1 个答案:

答案 0 :(得分:2)

你需要在这里使用url_for();它会为您生成各种/programme/<prog_id>网址。大概你在prog_id.json目录中有一系列bandsdaily个文件要链接到这里。

您需要获取所有可能prog_id值的列表,并对每个值使用url_for()

{% for prog_id in prog_ids %}
    {{ url_for('programme', prog_id=prog_id) }}
{% endfor %}

并将prog_ids作为列表传递给模板:

from flask import abort, render_template
import os.path


@cache.cached(timeout=86400)
@app.route('/programme/<prog_id>')
def programme(prog_id):
    path = os.path.join(my_location, "static/data/bandsdaily/")
    prog_ids = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
    if prog_id not in prog_ids:
        # no such file, return a not-found status
        abort(404)

    daily_bands = os.path.join(my_location, prog_id  + ".json")
    with open(daily_bands) as f:
        event_details = [json.loads(l) for l in f]

    return render_template('index.html', data=event_details, prog_ids=prog_ids)

如果404 Not Found文件不存在,此版本的视图也会返回prog_id状态。