简体   繁体   中英

Python - Flask Default Route possible?

In Cherrypy it's possible to do this:

@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. You can find it here .

Basically the decorator works by chaining two URL filters. 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:

@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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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