Python - Flask Default Route possible?
Asked Answered
C

4

44

In Cherrypy it's possible to do this:

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

Is there a flask equivalent?

Con answered 3/12, 2012 at 6:44 Comment(0)
Y
67

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
Yoder answered 3/12, 2012 at 6:56 Comment(2)
for some reason it doesn't work for me. It works for /, but when I try something else it returns 404Boesch
Works with Quart, too.Whereupon
D
9
@app.errorhandler(404)
def handle_404(e):
    # handle all other routes here
    return 'Not Found, but we HANDLED IT
Dyane answered 1/12, 2020 at 10:51 Comment(1)
Adding some explanations would improve the quality of your answer.Tichon
S
1

If you single page application has nested routes (e.g. 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')
Showpiece answered 18/11, 2019 at 21:18 Comment(0)
G
0

The below works for all requests, including PUT, PATCH and other unheard methods, wheres other answer don't

from flask import Flask
from werkzeug.routing import Rule

app = Flask(__name__)


@app.endpoint("catch_all")
def _404(_404):
    return "", 404


app.url_map.add(Rule("/", defaults={"_404": ""}, endpoint="catch_all"))
app.url_map.add(Rule("/<path:_404>", endpoint="catch_all"))

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080, debug=True)
Graduated answered 24/7, 2022 at 3:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.