简体   繁体   English

Python - Flask 默认路由可能吗?

[英]Python - Flask Default Route possible?

In Cherrypy it's possible to do this:在 Cherrypy 中可以这样做:

@cherrypy.expose
def default(self, url, *suburl, **kwarg):
    pass

Is there a flask equivalent?有等价的烧瓶吗?

There is a snippet on Flask's website about a 'catch-all' route for flask. Flask 的网站上有一段关于 Flask 的“包罗万象”路线的片段。 You can find it here . 你可以在这里找到它

Basically the decorator works by chaining two URL filters.基本上装饰器通过链接两个 URL 过滤器来工作。 The example on the page is:页面上的例子是:

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

Which would give you:这会给你:

% 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

If you single page application has nested routes (eg www.myapp.com/tabs/tab1 - typical in Ionic/Angular routing), you can extend the same logic like this:如果您的单页应用程序具有嵌套路由(例如 www.myapp.com/tabs/tab1 - 典型的 Ionic/Angular 路由),您可以像这样扩展相同的逻辑:

@app.route('/', defaults={'path1': '', 'path2': ''})
@app.route('/<path:path1>', defaults={'path2': ''})
@app.route('/<path:path1>/<path:path2>')
def catch_all(path1, path2):
    return app.send_static_file('index.html')
@app.errorhandler(404)
def handle_404(e):
    # handle all other routes here
    return 'Not Found, but we HANDLED IT

Try this试试这个

@app.route('/')
def entry():
    return redirect('/defaultroute')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM