我们说我创建了一个博客,它有三个静态路由,这些路由像往常一样设置。如果没有任何静态路由匹配,我希望我的方法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)
一些示例网址为:
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。
答案 0 :(得分:2)
首先使用静态路由定义您的路线,它将起作用。路由器将寻找最佳匹配并将其返回。
-> 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中是邪恶的)。
答案 1 :(得分: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)
现在您可以访问:
/
/约
/接触
/ anything_else