Python - Flask默认路由可能吗?

Joh*_*ang 21 python cherrypy flask

在Cherrypy中,可以这样做:

@cherrypy.expose
def default(self, url, *suburl, **kwarg):
    pass
Run Code Online (Sandbox Code Playgroud)

是否有相同的烧瓶?

ale*_*gui 35

Flask的网站上有一个关于烧瓶的"全能"路线的片段.你可以在这里找到它.

基本上,装饰器通过链接两个URL过滤器来工作.页面上的示例是:

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return 'You want path: %s' % path
Run Code Online (Sandbox Code Playgroud)

哪个会给你:

% curl 127.0.0.1:5000          # Matches the first rule
You want path:  
% curl 127.0.0.1:5000/foo/bar  # Matches the second rule
You want path: foo/bar
Run Code Online (Sandbox Code Playgroud)

  • 由于某种原因它对我不起作用。它适用于 /,但是当我尝试其他东西时它返回 404 (9认同)
  • 这不起作用 (3认同)

小智 7

@app.errorhandler(404)
def handle_404(e):
    # handle all other routes here
    return 'Not Found, but we HANDLED IT
Run Code Online (Sandbox Code Playgroud)

  • 添加一些解释会提高答案的质量。 (6认同)