gpt4 book ai didi

python - 使用Flask解决静态路由和动态路由的冲突

转载 作者:行者123 更新时间:2023-11-28 17:46:51 26 4
gpt4 key购买 nike

假设我创建了一个博客,它有三个照常设置的静态路由。如果没有任何静态路由匹配,我希望我的方法 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。

最佳答案

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

-> 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 中是邪恶的)。

关于python - 使用Flask解决静态路由和动态路由的冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16903683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com