3

假设我创建了一个博客,它有三个像往常一样设置的静态路由。如果没有任何静态路由匹配,我希望我的方法 post_page() 通过在数据库中查找博客文章来返回答案:

/                  → def index_page(): return "Index page"
/about             → def index_page(): return "About page"
/contact           → def index_page(): return "Contact page"
/<somethingelse>   → def post_page(): return get_content(somethingelse)

一些示例 URL 将是:

http://localhost/                                 → show the index page
http://localhost/about                            → show the about page
http://localhost/contact                          → show the contact page
http://localhost/the-largest-known-prime-number   → shows my log about the largest known prime number, it is fetched from the database.
http://localhost/my-cat                           → shows my log about my cat
http://localhost/my-dog                           → shows my log about my dog

使用 Flask 执行此操作的最佳方法是什么?如果可能的话,我仍然希望能够使用它url_for('about')来查找我的静态路由的 URL。

4

2 回答 2

3

只需先使用静态路由定义您的路由,它就会起作用。路由器将寻找最佳匹配并将其返回。

-> request comes in with /contact
|  /contact is in the routes
<- return call to contact function

-> request comes in with /foo-bar
|  /foo-bar matches the "postPage" route's regexp
<- return call to `postPage` function

旁注:请参阅http://www.python.org/dev/peps/pep-0008/关于您的函数名称(骆驼大小写在 Python 中是邪恶的)。

于 2013-06-03T19:41:27.327 回答
0

似乎您想对静态和动态都使用 1 个视图。使用您的示例,它将类似于

static_page_list = ['about','contact']

@app.route('/')
@app.route('/<static_page>')
def hello(static_page=None):
    if static_page not in static_page_list:
        return get_content(somethingelse)
    else
        static_page_html = static_page + ".html"
        return render_template(static_page_html)

现在您可以访问:

/

/关于

/接触

/还要别的吗

于 2013-06-03T20:55:44.500 回答