2012-10-31 73 views
3

我正在用Python構建一個網站(使用heroku),我想創建一個「最新的提交」部分。也就是說,當我在我的Python應用程序中創建一個新的@app.route(blah)時,我想要一個到新頁面的鏈接,顯示在我的主頁上的「最新提交」部分下。顯示創建新網頁的鏈接

這可能嗎?

編輯:這裏是我的代碼

import os 
import json 
from flask import Flask, render_template, url_for 
from werkzeug.routing import Map, Rule, NotFound, RequestRedirect, BaseConverter 

app = Flask(__name__) 


@app.route('/') 
def index(): 
    return render_template('welcome.html') 

@app.route('/about', endpoint='about') 
def index(): 
    return render_template('about.html') 

@app.route('/contact', endpoint='contact') 
def index(): 
    return render_template('contact.html') 

@app.route('/all-links', endpoint='all-links') 
def all_links(): 
    links = [] 
    for rule in app.url_map.iter_rules(): 
     url = url_for(rule.endpoint) 
     links.append((url, rule.endpoint)) 
    return render_template('all_links.html', links=links) 



if __name__ == '__main__': 
    # Bind to PORT if defined, otherwise default to 5000. 
    port = int(os.environ.get('PORT', 5000)) 
    app.run(host='0.0.0.0', port=port) 

和所有的應用程序的路線都存儲在app.url_map的all_links.html文件

<!DOCTYPE HTML> 
<html lang="en"> 
    <head> 
     <title>links</title> 
    </head> 
    <body> 
     <ul> 
      {% for url, endpoint in links %} 
      <li><a href="{{ url }}">{{ endpoint }}</a></li> 
      {% endfor %} 
     </ul>  
    </body> 
</html> 
+1

'這是可能的'有?如果你發佈了一些你已經嘗試過的代碼,你可能會得到更好的迴應。 – John

+0

在這一點上,我正在尋找更多的方向,而不是實際的「這是答案」的答案。我可以在燒瓶中完全做到這一點嗎?我的主要app.py文件中是否使用了python編碼和燒瓶編碼的組合? –

+0

Flask *是Python ;-) –

回答

7

這是werkzeug.routing.Map一個實例。話雖這麼說,你可以通過使用iter_rules方法在Rule實例迭代:

from flask import Flask, render_template, url_for 

app = Flask(__name__) 

@app.route("/all-links") 
def all_links(): 
    links = [] 
    for rule in app.url_map.iter_rules(): 
     if len(rule.defaults) >= len(rule.arguments): 
      url = url_for(rule.endpoint, **(rule.defaults or {})) 
      links.append((url, rule.endpoint)) 
    return render_template("all_links.html", links=links) 

 

{# all_links.html #} 
<ul> 
{% for url, endpoint in links %} 
<li><a href="{{ url }}">{{ endpoint }}</a></li> 
{% endfor %} 
</ul> 
+0

因此,您發佈的代碼中的for循環會將app.url_map中的所有路由都放入鏈接列表中。但render_template(「all_links.html」,links = links)的意義何在?這不是因爲當有人去那裏時,位於herokuapp.com/all-links的某個頁面返回all_links.html嗎? –

+0

@CrossGameChat - 最後一行只是一個例子 - 我將爲'all_links'模板添加一個Jinja模板示例。 –

+0

非常感謝您的幫助!我仍然收到500內部服務器錯誤「服務器遇到內部錯誤,無法完成您的請求。服務器過載或應用程序出現錯誤。」我用我的app.py和all_links.html的代碼更新了這篇文章 –

相關問題