【问题标题】:Get list of routes of a Flask function获取 Flask 函数的路由列表
【发布时间】:2014-03-25 06:44:55
【问题描述】:

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

例如:

/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(),但我认为后者用于其他目的。

【问题讨论】:

    标签: python twitter-bootstrap dynamic flask


    【解决方案1】:

    你需要在这里使用url_for();它会为你生成各种/programme/&lt;prog_id&gt; url。大概您的bandsdaily 目录中有一系列prog_id.json 文件要链接到此处。

    您需要获取所有可能的 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)
    

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

    【讨论】:

    • 感谢它快速、详细且非常有帮助。我添加/修改了这段代码:prog_ids = [os.path.splitext(filename)[0] for filename in os.listdir(path) if os.path.isfile(os.path.join(path, filename))]prog_ids.sort(key=lambda x: datetime.strptime(x, '%d%m%Y'))
    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多